简体   繁体   中英

Using JavaScript RegExp to valid email. Regex special characters not working

I've got this JavaScript function:

function emailaddresscheck() {
        var emailregex = new RegExp("[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
        var emailstring = $("#email-address").val();
        if (emailregex.test(emailstring)) {
            $("#email-address-check").fadeIn(100);
            return true;
        }
        else if ($("#email-address").val().length <= 5) {
            $("#email-address-check").fadeOut(100);
            return false;
        }
    }

The if condition is firing if I have a simple string in the RegExp constructor but this more complex regex isn't working.

Where am I going wrong?

UPDATE:

This is the finished working code:

function emailaddresscheck() {
        var emailregexp = new RegExp("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.(?:[A-Za-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$");
        var emailstring = $("#email-address").val();
        if (emailregexp.test(emailstring) === true) {
            $("#email-address-check").fadeIn(100);
            return true;
        }
        else if (emailregexp.test(emailstring) === false) {
            $("#email-address-check").fadeOut(100);
            return false;
        }
    }

When you create a regex with the RegExp constructor you need to double escape special characters since they are inside a string.

new RegExp("[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)");
                                     -^-    

Or just use a literal regex:

/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)/

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