This little HTML5 password field works perfectly WITHOUT the oninvalid attribute (the pattern say: minimum 6 characters):
<form>
<input type="password" name="user_password_new" pattern=".{6,}" required />
<input type="submit" name="register" value="Register" />
</form>
See the jsFiddle here.
But when I add an oninvalid attribute that gives out a custom error message when user's input does not fit the pattern, the entire field NEVER becomes valid, see the code here:
<form>
<input type="password" name="user_password_new" pattern=".{6,}" oninvalid="setCustomValidity('Minimum length is 6 characters')" required />
<input type="submit" name="register" value="Register" />
</form>
See the jsFiddle here.
Can you spot the mistake ?
I like to use like this:
And unplugged for all of valid input data
UPD, one more thing for better work:
If you set a value with
setCustomValidity()
then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to allow for the effects of any other validations you have to clear the custom validity:Although the answers for this question had good information, they weren't sufficient for my needs. I need to display different messages depending on which validity rule failed. In the other examples, the same validation failure message is used for all valiation failures.
The "validity" property of a form object holds the key to creating more than one validation failure message.
You can review all of the different "validity" property properties at this web site.
https://www.w3schools.com/js/js_validation_api.asp
This example shows how to display two different validation messages. If you uncomment the console.log() line below you can watch the validity property change as you type in a field.
NOTE: Some validity checks are "type" specific. For example, the "rangeOverflow", "rangeUnderflow", and "stepMismatch" attributes get set if type uses them; type="number".
You can use
title
as long as you don't mind having'You must use this format:'
before your message. If you want a full custom message, thesetCustomValidity()
worked for me.Since I stumbled on the same problem, here is my solution – tested and working with FF, Chrome, IE 10, Edge (Feb 2017).
Explanation:
setCustomValidity('');
removes the custom error string which otherwise would always result in an invalid field at the validation process.checkValidity();
does a manual validation – the same as it is happening at the form submisson. The result is stored invalidity.valid
.The second
setCustomValidity(validity.valid ? '' :'please enter 1234');
now sets the error string according to the validation result. If the field is valid it needs to be empty, otherwise the custom error string can be set.