I have a Message.uuid field which I want to add validations for which include:
Supported:
- A-Z, a-z, 0-9
- dashes in the middle but never starting or ending in a dash.
- At least 5, no more than 500 characters
What is the best way in rails to write a model validation for these rules?
Thanks
UPDATE:
validates :uuid,
:length => { :within => 5..500 },
:format => { :with => /[A-Za-z\d][-A-Za-z\d]{3,498}[A-Za-z\d]/ }
With a valid UUID this is failing
I’d leave the length validation up to a
validates_length_ofvalidator, so that you get more specific error messages. This will do two things for you: Simplify the regex used with yourvalidates_format_ofvalidator, and provide a length-specific error message when the uuid is too short/long rather than showing the length error as a “format” error.Try the following:
You can combine the two validations into a single
validateswith Rails 3: