Rails ActiveRecord regex for optional fields

I would like to check a field with a regex, and also let it be empty (accept an empty string). So far, the only thing I have managed to do is to write a regular expression that allows an empty string, for example:

validates :field, format: { with: /\A([az]+|)\z/i } 

Now this cannot be the right way - it seems like an ugly hack. I would like to know if there is another (correct) approach?

+6
source share
2 answers

allow_blank should work. (There is also allow_nil to accept only nil values โ€‹โ€‹(and not an empty string))

 validates :field, format: { with: /\A([az]+|)\z/i }, :allow_blank => true 
+10
source

You don't need interleaving ... you can use the '*' quantifier to indicate "zero or more." Also, I would use '\ w' rather than [az] ... this will force alphanumeric characters.

  validates :field, format: { with: /\A(\w*)\z/i } 
0
source

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


All Articles