0

I was using some pre-existing open source code and wanted to add a telephone validation to a form. The original code did not have a telephone validation. I tried to mirror the email php validation but modifry the preg-match for telephone digits, spaces, brackets and hyphens. The form still works fine except that it is not validating the telephone section. From testing the form, I can confirm that the telephone addition to the form is not being recognized (I know this because I tried copying the email validation into the telephone code and it did not recognize that either). My code is below. I am certainly a beginner with php and really only use php for handling the emailing of forms. Any guidance is appreciated. I am hoping to achieve the telephone validating correctly when the form is submitted.

Code:

<?php

// Set email variables
$email_to = '[email protected]';
$email_subject = 'New email from form';

// Set required fields
$required_fields = array('firstName','lastName','telephone','email','comment');

// set error messages
$error_messages = array(
    'firstName' => 'Please enter your first name to proceed.',
    'lastName' => 'Please enter your last name to proceed.',
    'email' => 'Please enter a valid email address to proceed.',
    'telephone' => 'Please enter a valid telephone number to proceed.',
    '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);
        
        // validate the telephone supplied
        if($field == 'telephone') if(!validate_telephone($_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";
        }
        
        // simple telephone content
        foreach($_POST as $key => $value) {
            if($key != 'submit') $telephone_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));
}

function validate_telephone($telephone = FALSE) {
    return (preg_match('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', $telephone))? TRUE : FALSE;
}

?>

I have tried copying the code from the email validation and changing the variables to $telephone. I then took the preg_match validaiton code and replaced it with a telephone validation code ('/^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/'). When the form is submitted, any text you add to the telephone form box is accepted and emailed.

The expecation I had was that the form would return a message in the form stating "Please enter a valid telephone number to proceed."

5
  • I’m not sure on your problem but I have some general notes. First, your RegEx doesn’t fully pass, see the last two examples. Second, I tend to start my number with a leading 1, even though I’m US and usually filling out forms in the US. Third, I have an extension which I want people to call. Commented Oct 27, 2022 at 3:25
  • Could you share the form code or better a dump of the $_POST variable with a phone number that shouldn't pass the test? Commented Oct 27, 2022 at 7:04
  • Hello BI457Xor, when I enter information into the telephone section in the form, it will output whatever is entered. So, numbers, letters or any information entered into the telephone section will be outputted and captured in an email that the PHP handles. The code listed above is located above the <html> on my page. Within the form, I also have the following code for the telephone section, listed in the below comment: Commented Oct 28, 2022 at 2:30
  • <div class="ContactPageEntry"> <!-- <input class="Form_Text" type="text" placeholder="TELEPHONE NUMBER" name="telephone"> --> <input class="Form_Text" type="text" placeholder="TELEPHONE" id="telephone" name="telephone" value="<?php echo isset($_POST['telephone'])? $_POST['telephone'] : ''; ?>" /> <?php if(in_array('telephone', $validation)): ?><span class="error"><?php echo $error_messages['telephone']; ?></span><?php endif; ?> </div> Commented Oct 28, 2022 at 2:32
  • I put your code on my local server and I get the error message "Please enter a valid telephone number to proceed.". The problem is probably elsewhere. Is there other code that could change the behaviour? Commented Oct 31, 2022 at 7:58

0

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.