1

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

2
  • You need to anchor your regular expression between ^ and $, or something like "@%#@#$AAAAA@#%@#$" will pass. Commented Aug 31, 2011 at 19:21
  • You should also limit the scope of your format validator; you currently attempting to validate length twice, and a UUID like AAA will cause two errors: one about the length, and one about the format. You probably only want it to cause a length error. Commented Aug 31, 2011 at 19:24

2 Answers 2

7

I'd leave the length validation up to a validates_length_of validator, so that you get more specific error messages. This will do two things for you: Simplify the regex used with your validates_format_of validator, 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:

validates_length_of :uuid, :within => 5..500
validates_format_of :uuid, :with => /^[a-z0-9]+[-a-z0-9]*[a-z0-9]+$/i

You can combine the two validations into a single validates with Rails 3:

validates :uuid,
    :length => { :within => 5..500 },
    :format => { :with => /^[a-z0-9][-a-z0-9]*[a-z0-9]$/i }
Sign up to request clarification or add additional context in comments.

5 Comments

Aren't you missing the caps here?
@Benoit I was, briefly, but remembered the /i on the regex which ignores case.
Just tried this but it doesn't seem to be working, it keeps redirecting. I've pasted the code I'm using above. Thoughts?
Even just using the validates_length_of with a input of 123412 is causing a redirect
@ColdTree Validators don't cause redirects. Models don't even cause redirects. Whatever problem your encountering, it has nothing to do with your models. Try running rails console and creating a Message with an invalid UUID, and checking which errors it has.
2

Use:

validates :uuid, :format => {:with => /my regexp/}

As for the regexp, you've already asked for it in another question.

Comments

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.