Regular expressions can be used to check the format of input values such as phone numbers and email addresses.
If a value other than the specified character string or sequence is entered, it will be caught in the validation check.
This time, I want to allow validation to pass even if the specified regular expression or blank is left as an optional input item.
This time, using the phone number as an example, let's first validate the phone number.
validates :phone_number, format: { with: /\A\d{10,11}\z/ }
This is a regular expression that means enter a 10- or 11-digit half-width number without hyphens.
This time, I want to enter the phone number arbitrarily, so I didn't write presence: true, so I thought it would be okay as it is ...
Validation with the specified regular expression broke through, and when I proceeded with the input field blank, I got stuck in validation!
Apparently, if you validate with a regular expression, it will not accept input other than the regular expression even if it is blank (nil).
Ask the mentor and use a custom method
It was said that there is a way to create a custom method such as "empty or 10 or 11 digit half-width number", but when I look into the custom method, it seems to be very annoying and difficult.
↓ Reference article for custom methods https://qiita.com/h1kita/items/772b81a1cc066e67930e
So, as a result of trial and error, I wondered if there was another method myself, and found a very simple solution.
Just add allow_blank: true as shown below.
validates :phone_number, format: { with: /\A\d{10,11}\z/ }, allow_blank: true
This literally means that you can leave it blank.
Now you can validate without entering a phone number!
If you want the input value to pass the validation with a regular expression or blank, add allow_blank: true.
Recommended Posts