This can be done by defining your own error messages with setCustomValidity
.
What you would do is read the event onInvalid
that is launched when the field is invalid (eg if it is required but left empty, or if it has a pattern that is not met), check what went wrong and show a personalized message that you would define with setCustomValidity
. You should also add logic when changing the field to remove the message if the problem was solved.
Here I am going to leave an example for an email: it is verified that it is not empty, that it has an at sign (@) and that it has a ".com" after the @:
function comprobarNombre(valor, campo) {
var mensaje = "";
// comprobar los posibles errores
if (this.value == "") {
mensaje = "El email no puede estar vacío";
} else if (this.value.indexOf("@") < 0) {
mensaje = "El email debe contener una @";
} else if (this.value.indexOf(".com", this.value.indexOf("@")) < 0) {
mensaje = "El email debe contener .com detras de la @";
}
// mostrar/resetear mensaje (el mensaje se resetea poniendolo a "")
this.setCustomValidity(mensaje);
}
var email = document.querySelector("#email");
// cuando se cambie el valor del campo o sea incorrecto, mostrar/resetear mensaje
email.addEventListener("invalid", comprobarNombre);
email.addEventListener("input", comprobarNombre);
<form>
<input type="text" id="email" name="email" value="" required />
<input type="submit" value="Enviar" />
</form>
You can do the same for your email field, checking that it contains only one @, that the first character is not a ".", etc. (You could also put the type "email" at input
that will do many of those checks for you).