user4463692
user4463692

Reputation:

How can I allow a regex to be blank?

I'm trying to make a form that accepts only a valid email, or a blank email. I think it will be something along these lines:

EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i OR ""
validates :email, format: { with: EMAIL_REGEX }

or maybe

EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
BLANK_REGEX = 
validates :email, format: { with: EMAIL_REGEX OR BLANK_REGEX }

but I can't figure out the proper syntax. Does anyone know the right way to do this?

Upvotes: 2

Views: 559

Answers (2)

Higor Morais
Higor Morais

Reputation: 121

The approach pointed by @avinash-raj is perfect. However you can use allow_blank: true in your validates. Your code should be like this:

validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i}, allow_blank: true 

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174696

Just make your regex optional to make your regex to match blank email also.

EMAIL_REGEX = /\A(?:[\w+\-.]+@[a-z\d\-.]+\.[a-z]+)?\z/i

OR

EMAIL_REGEX = /^(?:[\w+\-.]+@[a-z\d\-.]+\.[a-z]+)?$/i

TO make a regex optional, enclose the whole regex inside a non-capturing group (?:...) and then add a ? next to that group.

Upvotes: 1

Related Questions