3therk1ll
3therk1ll

Reputation: 2421

Rails validating phone number regex

Trying to strengthen my user profile forms etc by adding effective regex's to ensure that valid emails, phone numbers etc are being used. I have the following regex, that works fine when tested on Rubular, however I get a syntax error when I add it to my model as below:

(^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$

validates_format_of :contactnr, with: (^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$, allow_blank => true

Upvotes: 0

Views: 3625

Answers (3)

3therk1ll
3therk1ll

Reputation: 2421

Both @Uri and @Pedro ad good points as to missing syntax and correctly wrapping the regex. Another issue I cam across once that was fixed was that the 'allow_blank' method needs to be a symbol. Working code below.

validates_format_of :contactnr, with: /\A((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?\Z/, :allow_blank => true

Upvotes: 2

Uri Agassi
Uri Agassi

Reputation: 37409

Ruby's literal regex is enclosed in //:

validates_format_of :contactnr, with: /^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/, allow_blank => true

From the documentation:

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98921

You missed the closing bracket ) before the end of line $

Try this:

(^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3})$

Take a look at this link, There are some UK phone number regular expressions there.

Upvotes: 2

Related Questions