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/

Jon
  • 4,925
  • 3
  • 28
  • 38
daniel__
  • 11,633
  • 15
  • 64
  • 91
  • 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. – sidyll Mar 15 '11 at 02:26
  • the reason is that i edit my code (it is bigger), and possibility have more }, my mistake, but the problem is other, thanks – daniel__ Mar 15 '11 at 02:27
  • i actually matches mine, and all i have in my address book – Valerij Mar 15 '11 at 02: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 – sidyll Mar 15 '11 at 02:34
  • It'd be great if you can provide the email address that isn't being validated. We can't see yours. – Jon Mar 15 '11 at 02:34
  • Regular expressions aren't great for email validation, see http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses – orip Mar 15 '11 at 02:34
  • the email is diel129@gmail.com that i use in the test, but any is accepted i think – daniel__ Mar 15 '11 at 02:35

2 Answers2

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.

Bryan
  • 2,870
  • 24
  • 39
  • 44
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 = [
    'a.valid.email@gmail.com',
    'asdf@asdf.com',
    'another@valid.email.address.com'
];

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.

Sean Adkinson
  • 8,425
  • 3
  • 45
  • 64