I want to be able to pass items that have been validated with regular expressions even if they are left blank

Introduction

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.

Let's validate the phone number

This time, using the phone number as an example, let's first validate the phone number. スクリーンショット 2020-05-17 17.37.14.png


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 ...

a problem occured

Validation with the specified regular expression broke through, and when I proceeded with the input field blank, I got stuck in validation! スクリーンショット 2020-05-17 17.40.01.png

Cause

Apparently, if you validate with a regular expression, it will not accept input other than the regular expression even if it is blank (nil).

Solution 1

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.

Solution 2

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!

Summary

If you want the input value to pass the validation with a regular expression or blank, add allow_blank: true.

Recommended Posts

I want to be able to pass items that have been validated with regular expressions even if they are left blank
I want to be able to think and write regular expressions myself. ..
I tried to be able to pass multiple objects with Ractor
I want to be able to read a file using refile with administrate [rails6]
I want to be eventually even in kotlin