0

So right now I'm attempting to create an HTML file that takes user phone number and then checks the input's format via PHP form checking. I've been trying to figure this out but I'm still not clear on what the format for an int with specified parameters would be.

(Duplicate question but different enough to say it's just some copy of other questions. Same question, different methods, different answers.)

My code: (Made a comment in the code where I'm uncertain what to do.)

if($_POST && isset($_POST['submit'], $_POST['name'], $_POST['phone'])) {

$name = $_POST['name'];
$phone = $_POST['phone'];

if(!$name) {
    $errorMsg = "Please enter your name";
} elseif(!$phone || !preg match("\d{3}[\-]\d{7}", $email)){//this line format is incorrect
    $errorMsg = "Please enter a valid phone number";
    exit;
}
?>

<html>
<body>
<form method="POST">

Name:<br>
<input type="text" name="name">
<br>

Phone:<br>
<input type="tel"
pattern="\d{3}[\-]\d{7}"
title="Phone Number (Format: 999-9999999)"
name="phone">

<input name="submit" type="submit" value="submit">


</form>
</body>
</html>
Ryan Tibbetts
  • 412
  • 1
  • 8
  • 22

2 Answers2

2

You are missing the _ in preg_match() and the delimiters for preg_match and you had the variable $email in preg_match instead of $phone. I also added if phone isn't 11 char cause the regex you had would allow trailing chars.

if(!$name) {
    $errorMsg = "Please enter your name";
} elseif(!$phone || !preg_match('~\d{3}[\-]\d{7}~', $phone) || strlen($phone) != 11){//this line format is incorrect
    $errorMsg = "Please enter a valid phone number";
    exit;
}
Fluinc
  • 491
  • 2
  • 10
0

regexp pattern should be enclosed in / or # - preg_match("/\d{3}[-]\d{7}/", $phone)

– u_mulder

This guy answered my question.

Ryan Tibbetts
  • 412
  • 1
  • 8
  • 22