How to Prevent Form Validation on Page Load & While Typing on Input Field (HTML Constraint Validation API)

javascript
Published on October 26, 2019

Use-Cases of this Tutorial

  • Know how to prevent showing error styling on page load and while typing on the input field (if using Constraint Validation API).

The Constraint Validation API is great for validating HTML forms. It passes the task of form validation to the browser itself rather than writing custom code. In general this is more a robust way of validation.

However validation with the Constraint Validation API happens immediately. Even on page load, user will see that the form fields have been given an error styling (user did not even start filling out the form). Even when the user starts typing, the form field will be marked as error. This behaviour may confuse the user.

The ideal behaviour of validating the form can be :

  • Do not validate the form on page load.
  • Do not show error styling to the form field when the user focuses on the field, or while typing.
  • Show the error styling to the form field when the user moves from the field, and the input is invalid.
  • Show error styling to all invalid fields when user tries to submit the form.

This ideal behaviour can be achieved with a bit of CSS and Javascript.

Demo

Download Codes

Our Sample HTML Form

<form id="sample-form" novalidate>
	<div>
	    <label>Name</label>
	    <input type="text" name="name" required />
	</div>
	<div>
	    <label>Email</label>
	    <input type="email" name="email" required />
	</div>
	<div>
	    <label>Zipcode</label>
	    <input type="text" name="zipcode" required pattern="^\d{5,6}(?:[-\s]\d{4})?$" />
	</div>
	<button>Submit</button>
</form>
  • The form contains one text field. This will be validated whether it is empty or not.
  • The form contains one email field. This will be validated whether it represents a valid email or not.
  • The form contains one text field to input a Zipcode of 5/6 digits. We have passed a regular expression as its pattern attribute to validate this field.
  • The form includes the novalidate attribute. This means that we are validating the form by ourselves, and we don't want the browser defaults for showing validation errors.

CSS & Javascript to be Included

  • To prevent error styling on form load, we can set non-error CSS styles for input elements that are not in focus, and are invalid.
  • To prevent error styling while user is typing input, we can set non-error styles for input elements that are in focus, and are invalid.
  • To show error styling for invalid input when user leaves from the input, we can check whether the field in valid or not (this can be done by registering to the blur event for each input). If the field in invalid, we can set a specific CSS class for it. The input field having this CSS class and having invalid input, will be styled as an error field.

CSS :

/* normal */
form input {
    border: 1px solid black;
}

/* normal */
form input:not(:focus):invalid {
    border: 1px solid black;
}

/* normal */
form input:focus:invalid {
    border: 1px solid black !important;
}

/* error */
form input.error-input:invalid {
    border: 1px solid red;
}

Javascript :

/* blur event for all input fields in form */
document.querySelectorAll("#sample-form input").forEach(function(element) {
    element.addEventListener('blur', function() {
        // if input field passes validation remove the error class, else add it
        if(this.checkValidity())
            this.classList.remove('error-input');
        else
            this.classList.add('error-input');
    });
});

/* submit event on form */
document.querySelector("#sample-form").addEventListener('submit', function(e) {
    // if form has not passed validation 
    if(!this.checkValidity()) {
        // check validation for each input field inside the form
        // if input field is valid then remove the error class, else add it
        this.querySelectorAll("input").forEach(function(element) {
            if(element.checkValidity())
                element.classList.remove('error-input');
            else
                element.classList.add('error-input');
        });

        alert('Error');
        e.preventDefault();
    }
});

The checkValidity() method can be called either on the form, or on specific input elements. If it passed validation, a boolean true is returned, otherwise false.

Notes

Obviously the above method is not the best, as it involves additional Javascript. But as of now there is no pure CSS solution available.

CSS Selectors Level 4 define :user-invalid pseudo-class, which will probably take care of this a future time.

In this Tutorial