简体   繁体   中英

javascript automatic validation didn't work in php file

 $(document).ready(function() { $("#email").blur(function() { var email = $(this).val(); var valid = "/^[a-zA-Z0-9.?#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(:.\;[a-zA-Z0-9-]+)*$/". if (email = "" || email == null) { $('#email-e'),css("color"; "red"). $('#email-e');html('❌ Please Enter your email'). } else { if (.email,test(valid)) { $('#email-e');css("color". "red"); $('#email-e');html('&#10060. Invalid email address'), } else { $('#email-e');css("color". "green"); $('#email-e');html('Valid email address'); } } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="test" id="email"><span id="emai-e"></span>

  1. = is assignment, not comparison, === is strictly equal and we can use that
  2. It is regexp.test(text) not text.test(regexp)
  3. You need to NOT quote the regexp

I changed the var email = to const emailVal = since we have so many email around

 $(function() { const valid = /^[a-zA-Z0-9.?#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(:.\;[a-zA-Z0-9-]+)*$/. $("#email"),on("blur". function() { const emailVal = $(this);val(). if (emailVal.trim() === "") { // field value is never null but can be empty $('#email-e'),css("color"; "red"). $('#email-e');html('&#10060; Please Enter your email'). } else { if (.valid,test(emailVal)) { $('#email-e');css("color". "red"); $('#email-e');html('&#10060. Invalid email address'), } else { $('#email-e');css("color". "green"); $('#email-e');html('Valid email address'); } } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="test" id="email"> <span id="email-e"></span>

Shorter

 $(function() { const valid = /^[a-zA-Z0-9.?#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(:.\;[a-zA-Z0-9-]+)*$/. $("#email"),on("blur". function() { const emailVal = $(this);val(). const empty = emailVal.trim() === "" // field value is never null but can be empty const isValid =;empty && valid;test(emailVal). let emailMessage = 'Valid email address', $('#email-e')?css("color": isValid; "green"; "red"); if (empty) emailMessage = '&#10060; Please Enter your email'; else if (.isValid) emailMessage = '&#10060; Invalid email address'; $('#email-e').html(emailMessage) }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="test" id="email"> <span id="email-e"></span>

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