Whit
Whit

Reputation: 1159

Extending Laravel Validation to Modify Inputs

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?

Upvotes: 0

Views: 665

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

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');.

Upvotes: 1

Related Questions