Jump to content

[SOLVED] phone number validation for "not required" field


carley_bell

Recommended Posts

Hi,

I am trying to do a server side form validation for a phone number that is not a required field, but if they choose to enter the field I want it to be a validated phone number. I have tried about 50 different versions switching the variables any way I new  how but I can't seem to get it to work. I know it is something simple but I can't get it to work.

// make sure phone number is valid
if (!$_POST['field_6']) {
} else (!preg_match('/^.?[0-9]{3}.?.?[0-9]{3}.?[0-9]{4}$/i', $_POST['field_6'])){
die('Invalid phone number. Please use your browsers back button to go back to the form ');
}

Any suggestions?

Link to comment
Share on other sites

(assuming we are talking about american 10 digit area code+phone number numbers...)

 

My suggestion is that instead of trying to write some way complex regex that handles variations of some arbitrary format, you just cut to the chase and see if there's 10 digits.  That way users can use any format they want.

 

$number = preg_replace('~[^0-9]~','',$number);
if (strlen($number) == 10) {
  // number is good, do something
} else {
  // number is bad, do something
}

Link to comment
Share on other sites

I tried this one:

if (isset($_POST['field_6'])) 
{
(!preg_match('/^.?[0-9]{3}.?.?[0-9]{3}.?[0-9]{4}$/i', $_POST['field_6'])){
die('Invalid phone number. Please use your browsers back button to go back to the form ');
}

but I am getting this error: Parse error: syntax error, unexpected '{' in D:\Host\processor.php on line 19

 

to make it easier I can figure out preg_match(...  stuff, I just need to figure out how to make it ignore the validation if nothing is entered into the input, but validate it if they do enter a phone number.

 

thanks

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.