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?