Mubashar Abbas Mubashar Abbas - 1 month ago 7
Javascript Question

HTML5 Form validation - error message customization

I have a form with an input like this.



<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">





Now the default validation messages work great. But I want to set custom messages for specific rules.

i.e. for rules like
required
minlength
maxlength
when each fails I want to provide a custom error message specific to the rule that failed.

I have tried
oninvalid="setCustomValidity('please enter something')"
but that sets that message for every rule.

How can I specify custom error messages for specific rules?

Answer

Use setCustomValidity property to change validation messages and validity property to find type of validation error

validity : A ValidityState object describing the validity state of the element.

Upon form load validate property is initialized for each form element and updated on every validation due to user events like keypress,change etc. Here you can find the possible values

var email = document.getElementById("mail");

if (email.validity.valueMissing) {
  email.setCustomValidity("Don't be shy !");
}
else{
  event.target.setCustomValidity("");
}

email.addEventListener("input", function (event) {

  if (email.validity.valueMissing) {
    event.target.setCustomValidity("Don't be shy !");
  }
  else{
    event.target.setCustomValidity("");
  }
});  

Demo https://jsfiddle.net/91kc2c9a/2/

Note: For some unknown reason email validation is not working in the above fiddle but should work fine locally

More on ValidityState here