How to Restrict the Phone Field to Only Accept Numbers

Would you like to restrict the Phone field to only accept numbers? By default, the International and Smart phone formats will allow you to enter letters, but will fail on validation when you tab out of the field.

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

Using a small code snippet you can easily disable any keyboard characters from being entered unless it’s a number. This means, that if they attempted to type in anything but numbers, the text would simply not be entered, thus, disabling the field until a number was 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

Restricting the phone field to numbers only

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

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

/**
 * Restrict the 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 anything except the 0-9 key entry.

And that’s all you need to restrict the Phone field to numbers only! 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.

Reference Action

wpforms_wp_footer_end

FAQ

Q: How can I limit the number of digits they enter?

A: The Smart and US formats for the phone field will already have some validation for the number of digits entered on a phone number, and will fail the form submission if there are too many digits in the field.