Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate if my model attribute does NOT match a regex?

I'm using Rails 5. How do I create a validation rule for my model that validset if the attribute does NOT match a pattern? I have this

validates_numericality_of :my_str, :with => /\d:\d/, :allow_blank = true

But what I really want to say is validate if the string does not match the regular expression.

like image 667
Dave Avatar asked Oct 17 '22 14:10

Dave


1 Answers

What I have understood is that you want the validation to pass if it's not a number so why dont you change the regex to match anything but numbers:

/^(?!\d)/

Using your code it would be

validates_format_of :my_str, :with => /^(?!\d)/, :allow_blank = true

Or:
as the documentation says

Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option.

So:

validates_format_of :my_str,format: { without => /\d:\d/},  allow_blank = true

with validates_format_of validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with or :without options

like image 176
Ryad Boubaker Avatar answered Oct 21 '22 07:10

Ryad Boubaker