Home > Mobile >  How To Display An Error Message When Input Does Not Match Regex?
How To Display An Error Message When Input Does Not Match Regex?

Time:04-26

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

CodePudding user response:

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

CodePudding user response:

Here is a more general use case that you can adapt for your situation. This case uses the RegExp test method. If you want something more specific, please provide more of your code in the question.

var input = "abc";
var regex = /z/;
//does input pass the test?
var validInput = regex.test(input);

if(!validInput){
    console.log("Test Failed.")
}

  • Related