I have created a model with several fields that should accept the same data format (strings, but can be anything, FWIW). I’d like to apply the same validation rule to all those fields. Of course, I can just go ahead and copy/paste stuff, but that would be against DRY principle, and common sense too…
I guess this one is pretty easy, but I’m a Rails newcomer/hipster, so excuse-moi for a trivial question. =)
So if you had say three fields to validate:
And you wanted them all to be validated? So something like this:
Edit: There are numerous different validation methods in Rails )and they’re wonderfully flexible). For the format of the field you can use
validates_format_of, and then use a Regular Expression to match against it. Here’s an example of matching an email:I’d check out the Active Record Validations and Callbacks guide; it provides comprehensive insight about a lot of the features Active Record provides in terms of validation. You can also check out the documentation here.