Form Validation for Phone Field

Hello! I’m learning php and have a form I’m working on with code I obtained from a great tutorial. The form is working great, but I’d like to edit it so that the Phone field not only validates with text in it, it will only validate if the entry is in the form of 000-000-0000. I need to be able to apply this to the code I already have.

Here is some code I have now that includes validation for the email field. How can I edit this so that it will apply what I need to the phone field. Thank you!

[php]<?php

// Set email variables
$email_to = ‘[email protected]’;
$email_subject = ‘Marketing Inquiry’;

// Set required fields
$required_fields = array(‘fullname’,‘address’,‘city’,‘state’,‘zip’,‘phone’,‘email’,‘comment’);

// set error messages
$error_messages = array(
‘fullname’ => ‘Please enter a Name to proceed.’,
‘address’ => ‘Please enter an Address to proceed.’,
‘city’ => ‘Please enter a City to proceed.’,
‘state’ => ‘Please enter a State to proceed.’,
‘zip’ => ‘Please enter a Valid Zip Code to proceed.’,
‘phone’ => ‘Please enter a Phone Number to proceed.’,
‘email’ => ‘Please enter a valid Email Address to continue.’,
‘comment’ => ‘Please enter your Message to continue.’
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));

// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {		
	// the field has been submitted?
	if(!array_key_exists($field, $_POST)) array_push($validation, $field);
	
	// check there is information in the field?
	if($_POST[$field] == '') array_push($validation, $field);
	
	
	// validate the email address supplied
	if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}

// basic validation result
if(count($validation) == 0) {
	// Prepare our content string
	$email_content = 'New Website Comment: ' . "\n\n";
	
	// simple email content
	foreach($_POST as $key => $value) {
		if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
	}
	
	// if validation passed ok then send the email
	mail($email_to, $email_subject, $email_content);
	
	// Update form switch
	$form_complete = TRUE;
}

}

function validate_email_address($email = FALSE) {
return (preg_match(’/^[^@\s]+@([-a-z0-9]+.)+[a-z]{2,}$/i’, $email))? TRUE : FALSE;
}

function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", “\n”, “%0a”, “%0d”, “Content-Type:”, “bcc:”,“to:”,“cc:”), ‘’, $field));
}

?>[/php]

I would advise to do it differently

Accept that users will not follow formatting rules, so you will be receiving phone numbers like this
000-000-0000
000-0000000
000000-0000
0000000000
000 000 0000
0000 000 000
00 00 00 00 00
…etc

Example:

[php]<?php
echo ‘

’;

/**

  • Changes formatting on phone numbers from storage to display
  • 8005460455 --> 800-546-0455
  • @param mixed $unformatted
  • @return string
    */
    function formatPhoneNumberForOutput ($unformatted) {
    return number_format($unformatted/10000, 4, ‘-’, ‘-’);
    }

// get some hopeless numbers from users
$numbers = [
‘456-123-7837’,
‘800-5460455’,
‘546045-7601’,
‘7837123456’,
‘123 800 7602’,
‘7837 800 123’,
‘45 54 13 00 54’
];

print_r(‘original:’);
print_r($numbers);

$cleanNumbers = [];
foreach ($numbers as $number) {
// remove everything but numbers, the resulting number is a clean number that can be stored (ie 8005460455)
$cleanNumbers[] = preg_replace(’/[^0-9]/’, ‘’, $number);
}

print_r(‘cleaned:’);
print_r($cleanNumbers);

print_r(‘display:’);
foreach ($cleanNumbers as $number) {
echo formatPhoneNumberForOutput($number) . ‘
’;
}[/php]

Output

original:Array ( [0] => 456-123-7837 [1] => 800-5460455 [2] => 546045-7601 [3] => 7837123456 [4] => 123 800 7602 [5] => 7837 800 123 [6] => 45 54 13 00 54 ) cleaned:Array ( [0] => 4561237837 [1] => 8005460455 [2] => 5460457601 [3] => 7837123456 [4] => 1238007602 [5] => 7837800123 [6] => 4554130054 ) display:456-123-7837 800-546-0455 546-045-7601 783-712-3456 123-800-7602 783-780-0123 455-413-0054

[hr]

Force formatting

[php]<?php
echo ‘

’;

// get some hopeless numbers from users
$numbers = [
‘456-123-7837’,
‘800-5460455’,
‘546045-7601’,
‘7837123456’,
‘123-800-7602’,
‘7837 800 123’,
‘45 54 13 00 54’
];

foreach ($numbers as $number) {
if (preg_match(’/^\d{3}[-]\d{3}[-]\d{4}$/’, $number)) {
echo $number . ’ is valid!
’;
} else {
echo $number . ’ is NOT valid
’;
}
}
[/php]

Output

456-123-7837 is valid! 800-5460455 is NOT valid 546045-7601 is NOT valid 7837123456 is NOT valid 123-800-7602 is valid! 7837 800 123 is NOT valid 45 54 13 00 54 is NOT valid

I just remembered, if you do it like in the first suggestion (I think you should), then you must remember the possibility of international numbers.

If your site/app may have to handle this you must add some logic to handle numbers of a different format, like +47 800 12345

You could store these as 004780012345, and then check in the outputFormat-function if they start with 00, then strip the first 00 and show it as +XX XX XX XX, or something

Okay. Now if I use option 1, which part of that do I add to my existing php that I posted here and where in that code should I put it? Also, how do I change my input field tag which now is:

<?php if(in_array('phone', $validation)): ?><?php echo $error_messages['phone']; ?><?php endif; ?>

THIS IS CORRECT PROGRAM

<?php // Set email variables $email_to = '[email protected]'; $email_subject = 'Marketing Inquiry'; // Set required fields $required_fields = array('fullname','address','city','state','zip','phone','email','comment'); // set error messages $error_messages = array( 'zip' => 'Please enter a Valid Zip Code to proceed.', 'phone' => 'Please enter a Phone Number to proceed.', 'email' => 'Please enter a valid Email Address to continue.', 'comment' => 'Please enter your Message to continue.' ); // Set form status $form_complete = FALSE; // configure validation array $validation = array(); // check form submittal if(!empty($_POST)) { // Sanitise POST array foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value)); // Loop into required fields and make sure they match our needs foreach($required_fields as $field) { // the field has been submitted? if(!array_key_exists($field, $_POST)) array_push($validation, $field); // check there is information in the field? if($_POST[$field] == '') array_push($validation, $field); // validate the email address supplied if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field); } // basic validation result if(count($validation) == 0) { // Prepare our content string $email_content = 'New Website Comment: ' . "\n\n"; // simple email content foreach($_POST as $key => $value) { if($key != 'submit') $email_content .= $key . ': ' . $value . "\n"; } // if validation passed ok then send the email mail($email_to, $email_subject, $email_content); // Update form switch $form_complete = TRUE; } } function validate_email_address($email = FALSE) { return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE; } function remove_email_injection($field = FALSE) { return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field)); } ?>
Sponsor our Newsletter | Privacy Policy | Terms of Service