johnnyX
johnnyX

Reputation: 75

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";
    }

Upvotes: 2

Views: 140

Answers (2)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27192

Try this its working :

$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";
    }

Upvotes: 2

vks
vks

Reputation: 67968

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

Use anchors to make an exact match.

Upvotes: 4

Related Questions