1

I need to validate few attributes in my model only when they are present in params while updating or creating the object.

 validates :attribute_a,format: {with: /some_regex/},  :if => lambda{ |object| object.attribute_a.present? }

Like attribute_a there are multiple attributes which may not be present while being created or updated.Instead of writing the validates statement for each of them,is there a way in which I can check the presence of multiple attributes and then validate every one with a common validation such as inclusion_inor format:{with:/some_regex/ }.

I wanted something like the following code which obviously is wrong.

validates :attribute_a,attribute_b,attribute_c,attribute_d,:format => {:with =>
 /some_regex/},  :if => lambda{ |object| object.attribute_name.present? }
2
  • By present in this case you mean not blank (nil/"")? Commented Sep 3, 2013 at 16:26
  • The attribute is not present.So it is not nil. Commented Sep 3, 2013 at 17:00

1 Answer 1

2

You can use validates_format_of:

validates_format_of :attr_a, :attr_b, 
    with: /someregexp/,
    allow_blank: true

The allow blank option means that the regexp doesn't have to match if the attribute is not present.

Sign up to request clarification or add additional context in comments.

1 Comment

Works.Silly question overall.My folly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.