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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.