开发者

how to do conditional validation in model

I need to validate a field called student_id in my rails app.

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:

 validates_presence_of :studnet_id
 validates_numericality_of :student_id, :only_integer => true
 validates_l开发者_StackOverflow中文版ength_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?


Assuming you mean "the field may be blank, but if it has a value it should be 14 digits":

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'. Is that what you mean, or did I mis-interpret the question?


It sounds like validates_format_of is exactly what you need. You can give it a regular expression that matches a string of 14 digits.


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; skip validation.

validates_numericality_of :student_id, :only_integer => true, :allow_blank => true
validates_length_of       :student_id, :is => 14, :allow_nil => true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜