Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate phone number with Symfony

Tags:

regex

symfony

I want to validate the phone nummer in a form. I would like to check so number and the "(" and ")" char are valid only. So user can fill in +31(0)600000000. The +31 is already preset in the form. The number only is possible with the code below, only how to add the two chars?

Or is there a standaard better way to validate phone number?

 @Assert\Length(min = 8, max = 20, minMessage = "min_lenght", maxMessage = "max_lenght")
 @Assert\Regex(pattern="/^[0-9]*$/", message="number_only") 
like image 566
Tom Avatar asked Mar 14 '16 20:03

Tom


2 Answers

If you need a good and robust validator for numbers, with advanced options to valudate, I will advice to use google lib https://github.com/googlei18n/libphonenumber, there is existed symfony2 bundle https://github.com/misd-service-development/phone-number-bundle and you can see there is a assert annotation:

use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;

/**
 * @AssertPhoneNumber
 */
private $phoneNumber;
like image 150
Evgeniy Kuzmin Avatar answered Nov 08 '22 23:11

Evgeniy Kuzmin


The regex you need is:

/^\(0\)[0-9]*$

or for the entire number

/^\+31\(0\)[0-9]*$

You can test and play around with your regex here (it also includes auto-generated explanations): https://www.regex101.com/r/gD0hE5/1

like image 34
Putr Avatar answered Nov 09 '22 01:11

Putr