jQuery and HTML5 validations together

|
| By Webner

When we use HTML5 validation on form fields like required attribute, input type email, pattern attribute etc, then form data is not submitted until all HTML5 validations are passed. But if we associate some jquery code to the submit button then form is submitted ignoring HTML5 validations, which can be a problem in most of the cases. But there is a solution for this.

Suppose we have following form:

<form name=”register”>
<input type=”text” name=”firstname” id=”firstname” required/>
<input type=”text” name=”lastname” id=”lastname” required/>
<input type=”email” name=”email” id=”email” required/>
<input type=”password” name=”password” id=”password” required/>
<input type=”phone” name=”phone” id=”phone” required pattern="^[0-9]+$" title="Enter number only"/>
<input type=”submit” name=”submit” id=”btn”/>
</form>

In the above form, we have used html5 validation like required attribute on several fields, pattern attribute defining regular expression on phone field etc.

Now, If we associate jQuery code to button click event like this:

$(‘#btn’).click(function()
{
alert(“hi”);
});

then HTML5 form validations are ignored, alert message is displayed, and after that form is submitted.

To solve this problem we need to call checkValidity function explicitly like in the code below:

$(‘#btn’).click(function()
{
if($("form")[0].checkValidity())
{
$.ajax(
{
// Put ajax code here.
});
}
});

In this way, initially HTML5 form validation is performed and then form is submitted using jQuery ajax.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

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