user2512324
user2512324

Reputation: 791

Rails validate multiple attributes lambda only if all of them present

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? }

Upvotes: 1

Views: 1303

Answers (1)

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 2

Related Questions