Explain Codes LogoExplain Codes Logo

Manually Triggering Form Validation using jQuery

javascript
form-validation
html5-validation
polyfills
Alex KataevbyAlex Kataev·Oct 29, 2024
TLDR

To instantly validate a form with jQuery, invoke:

$('form').validate();

When checking if the form is valid without submitting, use:

if ($('form').valid()) { // Eureka! Form is valid }

Initialize with .validate() and test with .valid(). Make sure to include the jQuery Validation Plugin. This process triggers the checks as if a submit action was taken, but gives you the flexibility to handle the result.

Step-by-step guide for form validation

Embrace HTML5 validation with JavaScript

On modern browsers, using:

document.querySelector('form').reportValidity();

For legacy browsers, use:

var form = document.querySelector('form'); if (form.checkValidity()) { // Great Scott! The form is valid } else { // Darn! The form is invalid }

Enlisting the help of polyfills

Consider a polyfill such as hyperform.js to ensure consistency across browsers.

Beautifying user experience

Trigger validation when an element loses focus:

$('input, select').on('blur', function () { $(this).valid(); // Whoops! You forgot something });

Catch the invalid event for custom error messages and styling:

$('input, select').on('invalid', function () { // Houston, we have a problem });

Progressing through multi-step forms

Validate a fieldset before progressing:

$('#nextStepButton').on('click', function () { var currentSection = $(this).closest('fieldset'); if (currentSection.find('input, select').valid()) { // Onto the next quest! } else { // Sorry, you shall not pass! } });

Taking control of form submissions

Use onsubmit to exercise control:

$('form').on('submit', function (e) { if (!this.checkValidity()) { e.preventDefault(); // Hold your horses! Stop form from submitting // Please fill in all the blanks } });

Diving deeper into form validation

Customizing validity messages

Know specific problems with the validity property and set custom messages via setCustomValidity():

var input = document.querySelector('input[type="email"]'); input.oninvalid = function() { if (this.validity.typeMismatch) { this.setCustomValidity('Trust me, this email doesn't fly.'); } };

Simulating a submit button

Create a transient submit button to invoke standard HTML5 validation rules without submitting:

var form = document.querySelector('form'); form.addEventListener('validate', function () { var button = form.appendChild(document.createElement('button')); button.click(); form.removeChild(button); // Now you see me, now you don't! });

Understanding cross-browser validation

Utilize caniuse.com to ensure the compatibility of form validation methods across browsers.

Making validation accessible

Ensure validation patterns don't disrupt the experience for assistive technology users. Error messages shouldn't cause abrupt focus changes, but should provide clear interface cues.