The form I’m trying to validate using the Constraint Validation API rules in Javascript is not working. My input is set to
type = "email"
however in my Javascript, I am unable to use the property I need which is validity.typeMismatch
. This is an exercise to help me understand client-side form validation better.
const email = document.getElementById("mail");
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.setCustomValidity("I am expecting an email address!");
} else {
email.setCustomValidity("");
}
});
body {
background-color: #fff;
color: #333;
font: 1em / 1.4 Helvetica Neue, Helvetica, Arial, sans-serif;
padding: 1em;
margin: 0;
}
* {
box-sizing: border-box;
}
input:valid {
border: 2px solid green;
}
input:invalid {
border: 2px solid red;
}
<body>
<form>
<label for="mail">I would like you to provide me with an e-mail address:</label>
<input type="email" id="mail" name="mail" minlength="10" required>
<button>Submit</button>
</form>
</body>
I tried using ValidityState
property, i expected it to allow me to use typeMismatch
, but that did not work.