Thursday, March 2, 2017

Different data for rules in laravel for the same field?

I have phone field in database.

On frontend it is displayed using inputmask plugin in the following format: +7(999)999-9999.

It is sent back to server in this format.

Rules

$rules = ['required', 'phone_with_plus7', 'unique:users,phone'];

Validator

Validator::extend("phone_with_plus7", function($attribute, $value, $parameters, $validator) {
         if( ! preg_match("/^\+7\(\d{3}\)\d{3}-\d{4}$/", $value) ) return false;
         return true;
     });

The problem is: unique rule does not work, because it generates wrong queries:

select count(*) as aggregate from `app_users` where `phone` = '+7(000)000-0000'

Instead it should be

select count(*) as aggregate from `app_users` where `phone` = '70000000000' -- phone number is normalized before saving it to database.

How to deal with it?

P.S. Frontend must show phones in this format anyway.




via Jackson J

Advertisement