How to Provide Additional Phone Field Validation

Overview

Would you like to provide additional Phone field validation for your Smart Phone form field? For example, if you’d like to prevent users from entering a toll-free number in your Phone field. With a small PHP snippet, you can easily add this additional validation.

Setup

Once you’ve added the Phone field to your form, you can just add this code snippet to your site.

For the purpose of this documentation, we’re going to prevent any phone number starting with 8 or +8.

/**
 * Custom phone field Validation on submit (reject defined prefixes).
 *
 * @link  https://wpforms.com/developers/how-to-provide-additional-phone-field-validation/
 *
 */

function my_wpforms_process_validate_phone( $field_id, $field_submit, $form_data ) {
   $prefixes = [ '8', '+8' ];
   $regexp = implode( '|', $prefixes );
   if ( preg_match( '/^[' . $regexp . ']/', (string) $field_submit ) ) {
      wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = 'The number should not start with "' . implode( '", "', $prefixes ) . '"';
   }
}
add_action( "wpforms_process_validate_phone", 'my_wpforms_process_validate_phone', 10, 3 );

When a visitor tries to use a toll-free number in your form, once they hit the Submit button, they will see the validation error.

By providing an additional phone field validation you can easily prevent toll-free numbers from being entered on your form.

And that’s it! You’ve successfully added additional validation for your Phone form field. Would you also like to prevent certain emails from being entered as well? Check out our tutorial on How to Restrict Email Domains.

Filter Reference: wpforms_process_validate_phone