Explain Codes LogoExplain Codes Logo

Trigger standard HTML validation (form) without using submit button?

javascript
form-validation
javascript-validation
html5-validation
Anton ShumikhinbyAnton Shumikhin·Jan 5, 2025
TLDR

Trigger HTML form validation using the reportValidity() method:

document.querySelector('form').reportValidity() // No hitch, form dispatch!

It returns: true when the form is valid, or prompts the user for corrections when it's invalid. No submit button is required.

Ensure your form elements are properly set up with required validation attributes such as required, type, and pattern.

Managing browser compatibility

While reportValidity() provides a simple validation check for modern browsers, we must consider how to handle older browsers that do not support it, such as Internet Explorer or Edge, to provide universal validation experience.

var form = document.querySelector('form'); //grab the form, no matter the platform if (!form.reportValidity || form.reportValidity()) { // IE or Edge: I've got your back! // Form is valid or reportValidity is not supported } else { // Invalid fields are found }

Enhancing validation feedback with JavaScript

Native HTML5 validations like the pattern attribute provide simple, regex-based rules. But let's enhance the user experience with a bit of our JavaScript magic for more complex validation requirements.

<input type="text" id="username" pattern="[a-zA-Z0-9]{5,}" title="5 or more alphanumeric characters" required> <!-- Nobody likes a short name... Do you, Tom? Oh, wait... -->

Directing user attention to errors

When our friend reportValidity() spots an invalid input, directing the user's attention to it can make their journey much smother:

const firstInvalid = form.querySelector(':invalid'); //first come, first served if (firstInvalid) { firstInvalid.focus(); // umm… attention please! }

Handling error messages manually

The default error messages can sometimes be unsatisfactory and possibly confuse our users. Let's manually take over this job and provide a helping hand with better, custom error messages:

form.addEventListener('invalid', (event) => { event.preventDefault(); displayCustomErrorMessage(event.target); }, true); // Be nice, let them know about their innocent mistakes.

Strategies for triggering validation

So, how do we actually kick start the validation process?

Preventing Form Submission

Before triggering our validation guards, halt the form submission by using the onsubmit attribute with return false;. Now we can run our checks peacefully, and proceed only when every field is in perfect shape.

<form onsubmit="return validateForm();"> ... </form>

The invisible submit button

An invisible submit button can jump in to save the day! It can trigger the validation process while also preventing the default form submission process, cleverly keeping data integrity intact.

<input type="submit" id="hiddenSubmit" style="display:none"> <!-- I may be hidden, but I'm important! -->

Employ JavaScript for form validation

Where reportValidity() falls short, checkValidity() completes the relay race. Activate it directly in JavaScript, and handle errors programmatically for better control over your validation process:

if (!form.checkValidity()) { displayErrors(); } // You shall not pass, errors!

Keep it light and clean

While libraries like jQuery can simplify our tasks sometimes, it’s better to avoid using it when not necessary. We all appreciate a clean, lean snippet of JavaScript, don't we?

applyForm.onsubmit = function() {return false;}; applyForm.checkValidity(); applyForm.reportValidity(); // No jQuery here, just some good old JavaScript.