简体   繁体   中英

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';
}

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 = "test@gmail.com";
console.log(emailchecker(emailAdress)); //return true

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM