Search code examples
phpregexvalidationphone-number

How to ensure full string validation with regex on phone number string?


So I am trying to validate phone numbers with the form xxx-xxx-xxxx where x is a digit. The problem I am having is I can enter more than 4 digits for the last group of numbers. Does anyone see what I am doing wrong?

$telNumPattern = '/[0-9]{3}-[0-9]{3}-[0-9]{4}/'; //regular expression to match xxx-xxx-xxxx
if (empty($_POST['telNum'])) {
    $errors['telNum'] = "*Your telephone number can't be empty";
}
else 
    if (!preg_match($telNumPattern, $_POST['telNum'])) {
        $errors['telNum'] = "*Your email must be in the form xxx-xxx-xxxx";
    }

Solution

  • $telNumPattern = '/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/';
    

    Use anchors to make an exact match.