How to Restrict Phone Field to Only Accept Numbers

Introduction

Would you like to restrict the Phone field to only accept numbers? By default, the Phone form field will accept letters, characters, and numbers but when you click to the next field a validation error would appear.

default phone validation error will show when you tab out of the field

Using a small code snippet you can easily change this field by not allowing users to enter any letters or special characters. When a user tries to enter a letter or special character the key would not be entered.

Creating the form

First, you’ll need to create a new form and add your fields. If you need any assistance in creating your form, please see this documentation.

create your form and add your fields

Adding the CSS class

Next, you’ll need to add a CSS class to the Phone form field. Whenever a Phone field with this class is used, it will only accept a numeric value.

By adding this CSS class to any form field that accepts the CSS classes, you can restrict that field to accept only numbers.

To add a CSS class, select the Phone form field you’ve added to your form and in the Advanced tab, add numbersOnly to the CSS Classes.

add the CSS class of numbersOnly to the Phone field

Adding the snippet to restrict the Phone field to only numbers

Now it’s time to add the snippet to your site that would restrict the field to only allow numbers.

If you need any help in adding snippets to your site, please review this tutorial.

/**
 * Restrict Phone Field to Only Accept Numbers.
 *
 * @link https://wpforms.com/developers/how-to-restrict-phone-field-to-only-accept-numbers/
 *
 */

function restrict_letters_in_phone_field( ) {
?>
	<script type="text/javascript">
		
		jQuery(document).ready(function () {    

			jQuery('.numbersOnly').keypress(function (e) {    
				var charCode = (e.which) ? e.which : event.keyCode    
				if (String.fromCharCode(charCode).match(/[^0-9]/g))    
					return false;                        
			});    
		});   
 
	</script>
<?php
}
add_action( 'wpforms_wp_footer_end', 'restrict_letters_in_phone_field', 30 );

This snippet will automatically search for any form field with the CSS class of numbersOnly and will prevent the default entering of characters unless it matches anything except the 0-9 key entry.

And that’s all you need! Would you like to make the phone number inside the email notifications a link? Take a look at our tutorial on How to Make Phone Numbers a Link in Email Notifications.

Action reference: wpforms_wp_footer_end