1

Why isn't this regular expression working? A correct email address does not pass the validation.

<script type="text/javascript">
$(document).ready(function() {

    var regex = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i );

    $('#submit').click(function () {    
        var name = $('input[name=name]');
        var email = $('input[name=email]');
        var website = $('input[name=website]');
        var comment = $('textarea[name=comment]'); 
        if ((!regex.test(email))) {
            email.addClass('hightlight');
            return false;
        } else 
            email.removeClass('hightlight');            
    }
}
}

link: http://emprego.herobo.com/

7
  • The regex is working, the problem is in your code. I don't know much about JavaScript, but at first glance what I see is an extra } flying by there. Commented Mar 15, 2011 at 2:26
  • the reason is that i edit my code (it is bigger), and possibility have more }, my mistake, but the problem is other, thanks Commented Mar 15, 2011 at 2:27
  • i actually matches mine, and all i have in my address book Commented Mar 15, 2011 at 2:31
  • 1
    Maybe you need to change !regex.test(email) to !regex.test(email.value) or something? Rough guess. If it is correct I'll post as answer Commented Mar 15, 2011 at 2:34
  • It'd be great if you can provide the email address that isn't being validated. We can't see yours. Commented Mar 15, 2011 at 2:34

2 Answers 2

5

You are calling the RegExp test method on a jQuery object instead of a string. Change your conditional from:

if ((!regex.test(email))) { ... }

to:

if ((!regex.test(email.val()))) { ... }

and it should work.

Sign up to request clarification or add additional context in comments.

Comments

1

For what email address are they failing? This regex appears to work:

var regex = new RegExp(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i );

var emails = [
    '[email protected]',
    '[email protected]',
    '[email protected]'
];

var str = '';
for (var i=0; i<emails.length; i++) {
    str += emails[i] + ': ' + regex.test(emails[i]) + "\n";
}
alert(str);

This produces an alert with "true" for each email.

1 Comment

you can see on the fly the website: link added

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.