Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord regex validation of non-mandatory fields

I'd like to validate a field with regex and also allow it to be blank (to accept an empty string). So far, the only thing I managed is to write a regex that allows an empty string, like:

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

Now, this can't be a proper way - this seems like an ugly hack. I'd like to know if there's another (proper) approach?

like image 466
aL3xa Avatar asked Mar 18 '12 16:03

aL3xa


1 Answers

allow_blank should work. (There is also allow_nil for accepting nil values only (not an empty string))

validates :field,
          format: { with: /\A([a-z]+|)\z/i }, :allow_blank => true
like image 106
Gazler Avatar answered Oct 13 '22 19:10

Gazler