0

I'm trying to extend the validator in Laravel to validate US phone numbers. My Regex allows for most types (777.777.7777, (777) 777-777, etc), but I want the validator to normalize them. Here is what I've got so far, but it isn't normalizing.

Validator::extend('phone', function($attribute, $value, $parameters)
{
    $value = trim($value);
    if ($value == '') { return true; }
    $match = '/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/';
    $replace = '/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/';
    $return = '($1) $2-$3';
    if (preg_match($match, $value)) 
    {
        return preg_replace($replace, $return, $value);
    } 
    else 
    {
        return false;
    }
});

I figured returning the normalized value might do this, but that doesn't work. How can a validator extension modify the original input?

1 Answer 1

1

I suggest you not to mutate input in the validator and keep it responsible for validating.

However you can achieve what you need using Session:

Validator::extend('phone', function($attribute, $value, $parameters)
{
    $value = trim($value);
    if ($value == '') { return true; }
    $match = '/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/';
    $replace = '/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/';
    $return = '($1) $2-$3';
    if (preg_match($match, $value)) 
    {
        Session::set('mutated', ['phone' => preg_replace($replace, $return, $value)]);
        return true;
    } 
    else 
    {
        return false;
    }
});

Then simply pull the data from Session::get('mutated'); array or with dot notation Session::get('mutated.phone');.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution is proving difficult to implement. Since I am using updateUniques from Ardent, it is automatically pulling in old input despite the override. I've tried save() and forceSave(), neither of which will work. I'm hoping I can get the Validator to mutate the input.
Input/Request doesn't offer methods to change obviously, because it's Input :) Better check on Ardent and try to refine their method in some way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.