Restrict Typing Invalid Data in Form Field using jQuery

By restricting users from typing invalid data we can minimize validation errors in earlier stage. Let us see an example to do this using jQuery.

In this example we are having two fields name and phone in our HTML form. In name field we can enter only alphabets and in phone only numbers are allowed. This can be restriction can be done by calling a jQuery function on the keypress event of the form fields.

We are also using the submit button enable disable script to do empty check on the blur event of input fields.

View Demo

restrict-invalid-data-using-jquery

HTML Form Restricted Fields

This is the HTML code for displaying a form containing name, phone fields in which the users are restricted to type valid data.

<form id="frm" method="post">
   <div class="input-group">Name <span class="name-validation validation-error"></span></div>
   <div>
        <input type="text" name="name" id="name" class="input-control" onblur="validate()" />
   </div>
    
   <div class="input-group">Phone <span class="phone-validation validation-error"></span></div>
   <div>
		<input type="text" name="phone" id="phone" class="input-control" onblur="validate()" />
   </div>

   <div>
        <button type="submit" name="btn-submit" id="btn-submit" disabled="disabled">Submit</button>
    </div>
</form>

jQuery onKeyPress Handle to Restrict User Data

This jQuery script is called on the key-press event of the form input fields. While typing on the name field, this function allow to enter alphabets by checking the key ASCII value. The script is,

$(document).ready(function() {
	$('#name').on('keypress', function(key) {
		if((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) {
			return false;	
		}
	});
	$('#phone').on('keypress', function(key) {
        if(key.charCode < 48 || key.charCode > 57) {
			return false;
		}
    });
});

View DemoDownload

This jQuery code tutorial was published on March 9, 2016.

↑ Back to Top