Html5 Form Validation - Error Message Customization
Solution 1:
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
Solution 2:
The oninvalid
event occurs when the input is invalid, in your case, the input is required and if it is empty, oninvalid
will occur. (see this)
And yes, maxlength
should be bigger than minlength
and instead of required=""
you can simply write required
if your code is like this (with an ID 'input-field'):
<input type="text" name="question" id="input-field" class="form-control" required="" minlength="4" maxlength="8" size="20" oninvalid="setCustomValidity('please enter something')">
You will need to add custom functions to check different validation and display different errors based on them.
The validator()
function bellow triggers when the input box loses focus and checks for its requirements, and the valdiator_two()
is triggered on every keypress in the input field:
var field = document.getElementById("input-field");
functionvalidator(){
if (field.value === "") {
alert("You can't leave this empty");
}
if (field.value !== "" && field.value.length < 4){
alert("You have to enter at least 4 character");
}
}
functionvalidator_two(){
if (field.value.length >= 8){
alert("You can't enter more than 8 character");
}
}
field.addEventListener("blur", validator);
field.addEventListener("input", validator_two);
<inputtype="text"name="question"id="input-field"class="form-control"required=""minlength="4"maxlength="8"size="20"oninvalid="setCustomValidity('please enter something')">
Post a Comment for "Html5 Form Validation - Error Message Customization"