I am trying to make a client side validation to ensure an email is in the correct format using the .match() function, however I am having an issue which I can't seem to find the cause of. The error message won't hide when a correctly formatted email address is inputted.
HTML
<form id="signupform">
<label for="email">Email:</label>
<input id="email" type="text"><br><br>
<p id="error-msg-invalid-email">Email is not Valid (Client Side Validation)</p>
</form>
JavaScript
const signupform = document.getElementById("signupform");
const errorMsgInvalidEmail = document.getElementById("error-msg-invalid-email");
signupform.addEventListener('submit', (e) => {
e.preventDefault();
checkInputs();
});
function checkInputs () {
const email = document.getElementById("email").value.trim();
const regx = /^([a-zA-Z0-9\._] )@([a-zA-Z0-9]) . ([a-z] )(. [a-z] )?$/;
if(email.match(regx)) {
errorMsgInvalidEmail.style.display = "none";
}else{
errorMsgInvalidEmail.style.display = "block";
}
};
I have also tried using the .test() function and that also didn't seem to work. The changes are shown below.
if(regx.test(email)) {
errorMsgInvalidEmail.style.display = "none";
return true;
}else{
errorMsgInvalidEmail.style.display = "block";
return true;
}
CodePudding user response:
Try This:
function checkInputs () {
const email = document.getElementById("email").value.trim();
const regx = /^[A-Za-z0-9._ \-\'] @[A-Za-z0-9.\-] \.[A-Za-z]{2,}$/;
if(email.match(regx)) {
errorMsgInvalidEmail.style.display = "none";
}else{
errorMsgInvalidEmail.style.display = "block";
}
};
CodePudding user response:
You've got an extra space in your regex after the period. Use:
const regx = /^([a-zA-Z0-9\._] )@([a-zA-Z0-9]) .([a-z] )(. [a-z] )?$/;
It may help you to use a regex validator, like https://regex101.com/.