How to check if my model attribute matches a regular expression?

I am using Rails 5. How do I create a validation rule for my model that is validset if the attribute does NOT match the template? I have it

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

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

+5
source share
1 answer

What I understood is that you want the check to pass if it's not a number, so why don't you change the regex to match anything other than numbers:

 /^(?!\d)/ 

Using your code, it will

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

Or:
as the documentation says

Alternatively, you may require that the specified attribute do not match the regular expression with the option: no option.

So:

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

with validates_format_of checks attribute values, checking to see if they match the given regular expression, which is set using the :with or :without options

+1
source

Source: https://habr.com/ru/post/1266607/


All Articles