[英]how to do conditional validation in model
I need to validate a field called student_id
in my rails app. 我需要在Rails应用程序中验证一个名为student_id
的字段。
The previous requirement is that: the field is mandatory and will be consist of 14 pure digits, so I put the following code into the students model file will satisfy my need: 先前的要求是:该字段是强制性的,并且将由14个纯数字组成,因此我将以下代码放入students模型文件中将满足我的需求:
validates_presence_of :studnet_id
validates_numericality_of :student_id, :only_integer => true
validates_length_of :student_id, :is => 14
buf if the requirement change to if the field exists it must consist of 14 pure digits, how can I implement the kind of conditional validation? buf如果需求更改为字段是否必须包含14个纯数字,我该如何实现这种条件验证?
Assuming you mean "the field may be blank, but if it has a value it should be 14 digits": 假设您的意思是“该字段可能为空,但如果有值,则应为14位数字”:
validates_numericality_of :student_id, :only_integer => true, :allow_blank => true
validates_length_of :student_id, :is => 14, :allow_blank => true
Note the 'allow_blank'. 注意“ allow_blank”。 Is that what you mean, or did I mis-interpret the question? 那是你的意思,还是我误解了这个问题?
It sounds like validates_format_of is exactly what you need. 听起来好像validates_format_of正是您所需要的。 You can give it a regular expression that matches a string of 14 digits. 您可以给它一个匹配14位数字字符串的正则表达式 。
For rails validation,there are some default validation options.One of them is :allow_nil
.The :allow_nil
defaulted value is false
.In the validates_length_of
the options :allow_nil
means that Attribute may be nil; 对于rails验证,有一些默认的验证选项。其中之一是:allow_nil
。 :allow_nil
默认值是false
。在validates_length_of
选项中:allow_nil
表示Attribute可以为nil。 skip validation. 跳过验证。
validates_numericality_of :student_id, :only_integer => true, :allow_blank => true
validates_length_of :student_id, :is => 14, :allow_nil => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.