Sometimes, we want to set custom HTML5 required field validation message with JavaScript
In this article, we’ll look at how to set custom HTML5 required field validation message with JavaScript.
How to set custom HTML5 required field validation message with JavaScript?
To set custom HTML5 required field validation message with JavaScript, we call the setCustomValidity
method.
For instance, we write
<form id="myform">
<input
id="email"
oninvalid="invalidMsg(this);"
name="email"
oninput="invalidMsg(this);"
type="email"
required="required"
/>
<input type="submit" />
</form>
to add a form with an input.
We set oninput
and oninvalid
to invalidMsg(this)
to call the invalidMsg
function to set the validation message when we type in a value or when it’s invalid respectively.
Then we write
function invalidMsg(textbox) {
if (textbox.value === "") {
textbox.setCustomValidity("Required email address");
} else if (textbox.validity.typeMismatch) {
textbox.setCustomValidity("please enter a valid email address");
} else {
textbox.setCustomValidity("");
}
return true;
}
to define the invalidMsg
function.
In it, we get the textbox
input and check if value
property for the input value.
If it’s empty, we set the validation message to "Required email address"
with setCustomValidity
.
If the input doesn’t match the type specified by the type attribute, typeMismatch
is true
, and we set a validation message for that with setCustomValidity
.
Otherwise, we call setCustomValidity
with an empty string to set it as valid.
Conclusion
To set custom HTML5 required field validation message with JavaScript, we call the setCustomValidity
method.