I'm trying to validate two input boxes and display a custom error message using HTML5 browser validation.
The validation doesn't seem to work with my second input, I'm always prompted with my custom error message. When I remove the oninvalid
it works.
Where am I going wrong?
My HTML is below;
<form>
<input type="text" placeholder="min 3" pattern=".{3,}">
<input type="text" placeholder="min 4" oninvalid="this.setCustomValidity('Must be 4 Characters')" pattern=".{4,}">
<input type="submit" value="Check"></input>
</form>
I'm sure it's something obvious.. any help is appreciated.
Here's a fiddle.
You could use the oninput
attribute to restore the validity of the form like this: oninput="setCustomValidity('')"
.
This has a side effect and it is that if you type an invalid input and submit the form and type again another invalid value immediately the default message is shown instead of the custom one until you click again the submit option.
(See this forked jsfiddle, or below working snippet)
<form>
<input type="text" pattern=".{3,}" placeholder="min 3">
<input type="text" placeholder="min 4" pattern=".{4,}" oninvalid="setCustomValidity('Must be 4 Characters')" oninput="setCustomValidity('')">
<input type="submit" value="Check" />
</form>
Another option would be adding an inline text with title
attribute. The text will be appended after the default error message (See below snippet)
<form>
<input type="text" pattern=".{3,}" placeholder="min 3">
<input type="text" placeholder="min 4" pattern=".{4,}" title="Must be 4 Characters">
<input type="submit" value="Check" />
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With