简体   繁体   中英

How to check if on input matches a string pattern with jQuery

My goal is to check if an email input field (as a user is typing characters into it), matches a pattern or not. This is my working example so far, but I feel stuck when it gets to the point of actually matching the process "while" typing...

Below is my working example which I'm trying to capitalize on...


   //...

    var $attemail = mtarget.find(".my-email-field"); //INPUT

    function validateEmail(email) {
      var re = /\S+@\S+\.\S+/;
      if (re.test(email) == false) {
        console.log('Email field is not valid');
        //issueFlag.push(noticeEmail);
      }
    }

    function checkEmailOnType() {
      $attemail.on("input", function(){
        var $characters = jQuer(this).val();

        if ($characters.toLowerCase())  {
            //IF MY CHARACTER TYPING IS PASSING OR NOT PASSING 
            //MY validateEmail() FUNCTION ABOVE, HOW DO WE SAY THAT?  
        }
      });
    }

    //...


Add a return value to your function. Yours as it is returns undefined which you can just change to return the result of re.test(email) .

//...

var $attemail = mtarget.find(".my-email-field"); //INPUT

function validateEmail(email) {
  var re = /\S+@\S+\.\S+/;
  return re.test(email)
}

//function checkEmailOnType() {
  $attemail.on("input", function(){
    var $characters = jQuer(this).val();

    if ($characters.toLowerCase())  {
        //IF MY CHARACTER TYPING IS PASSING OR NOT PASSING 
        //MY validateEmail() FUNCTION ABOVE, HOW DO WE SAY THAT?
        if(validateEmail($characters) == false){
            console.log('Email field is not valid')
        }
    }
  });
//}

//...

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