AnApprentice
AnApprentice

Reputation: 110950

Rails Validation that use validates a string with a regex?

I have a Message.uuid field which I want to add validations for which include:

Supported:

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

Upvotes: 1

Views: 2868

Answers (2)

user229044
user229044

Reputation: 239270

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 }

Upvotes: 7

Benoit Garret
Benoit Garret

Reputation: 13675

Use:

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

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

Upvotes: 2

Related Questions