10

I have the following regex that I use in my routes.rb for /type-in-something-here

# A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _
# At least 5, no more than 500 characters

In the routes this works well as:

match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/ }

I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb:

validates_format_of :uuid, :with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i, :message => "Invalid! Alphanumerics only."

But this validates_format_of isn't working, and instead of adding an error it's allow the record to save.

Any ideas what's wrong?

Thanks

3 Answers 3

17

For validation purposes, remember to add the beginning and end of string markers \A and \Z:

validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i

Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)

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

1 Comment

Note that using \Z at the end of the regex allows a trailing newline. You probably want \z instead. (Apologies for commenting on an old issue.)
11

using something like this

validates :uuid, :format => {:with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i},
                 :message => "your message"

For more check this

1 Comment

This works well for me, however the closing brace is in the incorrect place in this example. It should be: validates :uuid, :format => {:with => /.../i, :message => "..."}
5
validates :name, format: { with: /\A[a-zA-Z]+\z/,
message: "Only letters are allowed" }

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.