我正在使用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
with validates_format_of通过测试属性值是否与给定的正则表达式匹配来验证属性的值,该表达式使用:with或:without选项指定