Reputation: 3635
let email = document.getElementsByClassName("user-input__form-email")[0];
email.type = "email";
console.log("email " + email.value + " " + email.checkValidity());
if (email.checkValidity() === false) {
emailError.style.display = "block";
}
<input placeholder="Email Address" class="user-input__form-email">
For empty value for email input field, isn't checkValidity() should return false value ?
Upvotes: 0
Views: 1514
Reputation: 1701
The reason why checkValidity()
was returning true when empty is because the field was not required
thus the function thought, because it wasn't required, that empty is valid and it returned true.
I am using required
in order to not validate an empty input as true.
However, we all know how ugly the stock validation is by default, and you can disable this by adding novalidate
to your <form>
After a few edits and reading your comments, I think this is what you are looking for. A validation that shows your own custom error message if email.checkValidity()
returns false
let email = document.getElementsByClassName("user-input__form-email")[0];
email.type = "email";
function validate_email() {
if (!email.checkValidity()) {
document.getElementById("error").innerHTML = "E-mail is not correct";
return false;
} else {
document.getElementById("error").innerHTML = "";
return true;
}
}
console.log("email " + email.value + " " + email.checkValidity());
<form onsubmit="return validate_email(this)" novalidate>
<input placeholder="Email Address" class="user-input__form-email" required>
<p id="error" style="color: red;"></p>
<input type="submit" onsubmit="return validate_email(this)">
</form>
Upvotes: 1