'How To Display An Error Message When Input Does Not Match Regex?
I simply want to display an error message such as "Email must contain @" and prevent the form from submitting, if there is an error.
How can I go about doing this?
My latest attempt which is a failure:
const email = document.getElementById('email')
const emailmessage = document.getElementById('emailmessage')
const regex = ('^\S+@\S+$')
form.addEventListener('submit', function (event) {
if(!email.value.match(regex)) {
emailchecker();
event.preventDefault();
}
});
let emailchecker = function() {
if(!email.value.match(regex)) {
document.getElementById('emailmessage').innerHTML = '<img src="222.svg" height="15"/> Email Error';
}
Solution 1:[1]
Your code is correct, you only need the regex for email validation:
function emailchecker (emailAdress){
let regexEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (emailAdress.match(regexEmail)) {
return true;
} else {
return false;
}
}
let emailAdress = "[email protected]";
console.log(emailchecker(emailAdress)); //return true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abdelatif Laghjaj |
