Álvaro Franz
Álvaro Franz

Reputation: 811

Display form errors if the checkValidity() method returns false

Short version of the question

Is there a way to trigger the native browser form validation error feedback with Javascript?

Detailed version of the question

When trying to submit a form that has a required input field that has not been filled by the user, modern browsers handle the validation automatically, and display an error for the input field where an error has been found.

Each browser handles this in an own way, but to get an idea, here is how Edge is doing it today:

enter image description here

I want to achieve the same native validation feedback but without using the submit event.

According to the documentation for HTMLSelectElement.checkValidity(), I am able to know if the form does validate or not.

I could use this true/false information and handle the visual feedback by writing custom code, but I wonder if there is a way to trigger the native browser error feedback, so I can save time.

Did I try something?

Yes, I tried using a common submit button and using prevent default event to do what I like (and it works), but I want to know if there is a straight way to achieve this, something like HTMLSelectElement.displayErrors() would be logic.

UPDATE

In fact, the method does exist, it's called HTMLFormElement.reportValidity()

Upvotes: 5

Views: 4944

Answers (2)

Álvaro Franz
Álvaro Franz

Reputation: 811

Thanks to Emil's answer, I made it work the way I wanted.

I am leaving it here for further readers but accepting Emil's answer since that was the key part.

According to the docs, you can run the checkValidity() method on the form itself, not necessarily on the child input.

function processForm(){

    // Early return form processing if validation errors where found
    if(!document.getElementById('form-id').checkValidity()){
        document.getElementById('form-id').reportValidity();
        return false;
    }

    // Okay, all cool, do stuff...

}

Upvotes: 1

Emil Dimitrov
Emil Dimitrov

Reputation: 324

You can do it by calling reportValidity() on the given input field.

const input = document.querySelector('input');

input.addEventListener('input', (e) => {
  e.target.reportValidity();
});
<input type="email" >

Upvotes: 5

Related Questions