简体   繁体   中英

email input validation in Jquery

I need to validate the value of an e-mail input. I have this code but it doesn't work. Could you help me please?

HTML

<input type="text" name="mail" class="mail" /> 
<button class="validate">VALIDATE</button>

JQUERY

$(document).ready(function(){
    var setMail = $(".mail").val();
    var mailVal = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; 

    $(".validate").click(function(){
        if (mailVal == setMail) {
            alert("GOOD!");
            }
            else{ 
            alert("WRONG!");
            }
   });
});

JSFiddle: DEMO

You can use jQuery validation library. It does many validation for you with an easy implementation way. Such like-

$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      email: true
    }
  }
});

documentation source link- jQuery Validation

mailVal isn't going to equal setMail. You want to check for a match: mailVal.test($(".mail").val()) instead of the == test.

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