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>
8
  • 1
    if your form submit to the current page itself, you can actually take off the action attribute in your form Commented Nov 3, 2015 at 19:50
  • 2
    Are you really missing a _ between preg and match? Also, $email is not defined, did you mean $phone? Commented Nov 3, 2015 at 19:51
  • @Andrew Thanks! I didn't know that, I fixed that as well. Commented Nov 3, 2015 at 19:57
  • 4
    regexp pattern should be enclosed in / or # - preg_match("/\d{3}[\-]\d{7}/", $phone) Commented Nov 3, 2015 at 20:01
  • @u_mulder: Whaaaaa! We all missed that. Commented Nov 3, 2015 at 20:03

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

– u_mulder

This guy answered my question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.