我正在使用 Rails 5。如果属性与模式不匹配,我如何为我的模型创建验证规则?我有这个
validates_numericality_of :my_str, :with => /\d:\d/, :allow_blank = true
但我真正想说的是验证字符串是否与正则表达式不匹配。
最佳答案
我所理解的是,如果它不是数字,您希望验证通过,那么为什么不更改正则表达式以匹配除数字之外的任何内容:
/^(?!\d)/
使用您的代码将是
validates_format_of :my_str, :with => /^(?!\d)/, :allow_blank = true
或者:
如 documentation说
Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option.
所以:
validates_format_of :my_str,format: { without => /\d:\d/}, allow_blank = true
与
validates_format_of
通过测试属性值是否匹配给定的正则表达式来验证属性的值,该表达式使用 :with
指定。或 :without
选项
关于validation - 如何验证我的模型属性是否与正则表达式不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355364/