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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With