Restrict Typing Invalid Data in Form Field using jQuery

by Vincy. Last modified on July 12th, 2022.

By restricting users from typing invalid data we can minimize validation errors in an 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 the name field, we can enter only alphabets and in the 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

HTML Form Restricted Fields

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

restrict-invalid-data-using-jquery

<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 in the name field, this function allows entering 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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page