<form method="post" action="#">
<input type="text" pattern=".{5,}" name="el" oninvalid="setCustomValidity('Must Be Longer Than 5 Characters')" oninput="setCustomValidity('')"/>
<input type="submit"/>
</form>
so, without the oninput="setCustomValidity('')"
part, regardless of the input the form will never be submitted because it will always show the "Must Be Longer Than 5 Characters" error, but by using oninput="setCustomValidity('')"
everything works fine, however i don't seem to understand how oninvalid and oninput work together, if i am setting custom validity to ''
on input then how is the oninvalid
part not overwritten everytime the user presses a key ?
i think this has something to do with how setCustomValidity()
Works, no ?
<form method="post" action="#">
<input type="text" pattern=".{5,}" name="el" oninvalid="setCustomValidity('Must Be Longer Than 5 Characters')" oninput="setCustomValidity('')"/>
<input type="submit"/>
</form>
so, without the oninput="setCustomValidity('')"
part, regardless of the input the form will never be submitted because it will always show the "Must Be Longer Than 5 Characters" error, but by using oninput="setCustomValidity('')"
everything works fine, however i don't seem to understand how oninvalid and oninput work together, if i am setting custom validity to ''
on input then how is the oninvalid
part not overwritten everytime the user presses a key ?
i think this has something to do with how setCustomValidity()
Works, no ?
1 Answer
Reset to default 6Enter more than 5 characters and then click on submit, it would work. It will not work only in the cases, where the invalid event is fired at least once.
<form method="post" action="#">
<input type="text" pattern=".{5,}" name="el"
oninvalid="setCustomValidity('Must Be Longer Than 5 Characters');"/>
<input type="submit"/>
</form>
A few basics, reference mdn:
oninvalid
is triggered when the constraints are not satisfied.
setCustomValidity
method is used to set the result of the validation; an empty string means the constraint is satisfied, and any other string means there is an error.
Reason:
- Once the oninvalid
event is trigged you set the result using setCustomValidity
to be a non-empty string.
- Now even after(changing the input value) the pattern
condition is satisfied, the result of validation is a non-empty string.
- In your code oninvalid="setCustomValidity('...')" oninput="setCustomValidity('')"
, you clear the result after each input.