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?
Use
setCustomValidity
property to change validation messages andvalidity
property to find type of validation errorUpon 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 valuesDemo 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
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 thanminlength
and instead ofrequired=""
you can simply writerequired
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 thevaldiator_two()
is triggered on every keypress in the input field: