rails 3 验证字符串 [英] rails 3 validation of a string

查看:46
本文介绍了rails 3 验证字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以告诉 Rails 我的字符串可能不是某物"?

Is there any way to tell rails that my string may not be 'something'?

我正在寻找类似的东西

validates :string, :not => 'something'

谢谢团团

推荐答案

这些都可以完成工作(单击文档的方法):

Either of these will do the job (click on the methods for documentation):

  1. 可能是最好和最快的方法,易于扩展为其他词:

  1. Probably the best and fastest way, easy to extend for other words:

validates_exclusion_of :string, :in => %w[something]

  • 这有使用正则表达式的好处,因此您可以更轻松地进行概括:

  • This has a benefit of using a regexp, so you can generalise easier:

    validates_format_of :string, :without => /\A(something)\Z/
    

    你可以用 /\A(something|somethingelse|somemore)\Z/

    这是您可以实现任何验证的一般情况:

    This is the general case with which you can achieve any validation:

    validate :cant_be_something
    def cant_be_something
      errors.add(:string, "can't be something") if self.string == "something"
    end
    

  • 要准确地获得您提出的语法(validates :string, :not => "something"),您可以使用此代码(尽管警告,我在阅读rails 源代码的主分支,它应该可以工作,但它在我大约 3 个月大的安装中不起作用).将此添加到您的路径中的某个位置:

  • To get exactly the syntax you proposed (validates :string, :not => "something") you can use this code (a warning though, I discovered this while reading the master branch of the rails source and it should work, but it doesn't work on my ~ 3 months old install). Add this somewhere in your path:

    class NotValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
      end
    end
    

    这篇关于rails 3 验证字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆