Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
        }
    }
share|improve this question
2  
Could you post some input that isn't working please? –  Jonathan Henson May 31 '13 at 0:26
    
I can't because with this regex the JavaScript popup box won't open. –  Phillip May 31 '13 at 0:28

1 Answer 1

up vote 4 down vote accepted

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)/
share|improve this answer
    
Good answer, yours is better. I'm deleting mine. –  Jonathan Henson May 31 '13 at 0:34
    
Thanks for the info! Working great now! –  Phillip May 31 '13 at 1:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.