How to Restrict Numbers in a Single Line Text Form Field

Overview

Would you like to restrict your visitors from using a number in a particular text field? With a small PHP snippet, you can easily restrict a Single Line Text form field to accept letters only. In this tutorial, we’ll show you the necessary code snippet to restrict numbers in these fields.

Setup

Once you’ve set up your form and fields, the next step is to add this code snippet to your site.

In our example, we’re going to prevent numbers inside our Single Line Text form field $fields[11] for the form ID 1049.

/**
 * Disallow numbers in a single-line text field
 *
 * @link https://wpforms.com/developers/how-to-restrict-numbers-in-a-single-line-text-form-field/
 *
 */
function wpf_dev_process( $fields, $entry, $form_data ) {
      
    // Optional, you can limit to specific forms. Below, we restrict output to
    // form ID #1049.
    if ( absint( $form_data['id'] ) !== 1049 ) {
        return $fields;
    }
      
    // get value of the specific field ID and set it to a variable
    $mystring =   $fields[11]['value'];
	if (preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $mystring))        {
            // Add to global errors. This will stop form entry from being saved to the database.
            // Uncomment the line below if you need to display the error above the form.
            // wpforms()->process->errors[ $form_data['id'] ]['header'] = esc_html__( 'Some error occurred.', 'plugin-domain' );    
  
            // Check the field ID 4 and show error message at the top of form and under the specific field
               wpforms()->process->errors[ $form_data['id'] ] [ '11' ] = esc_html__( 'This field cannot accept numbers.', 'plugin-domain' );
  
            // Add additional logic (what to do if error is not displayed)
        }
    }
add_action( 'wpforms_process', 'wpf_dev_process', 10, 3 );

And that’s it! When your visitors try to input a number into that field, they will see an error message on the form when the form submits.

now you can restrict numbers in a single line text form field

Would you also like to prevent special characters from being entered into a Single Line Text form field? Check out the tutorial on How to Restrict Special Characters From a Form Field.

Action Reference: wpforms_process