egis
egis

Reputation: 1412

javascript regex - whats wrong with my very simple regex?

I want to validate email address in html form. I have very little knowledge in regex.

Validation is very simple, just to match any_symbols@any_symbols.two_to_eight_symbols pattern.

Here is the regex I'm trying to use ^.+@.+\..{2,8}$. Yet it doesn't work, it validates pattern any_symbols@four_symbols.

Note: do not worry about such simple validation, on server side I'm doing filter_var (php) and sending token to that email. Just need to enable button on form when inputed email address fits some sane pattern :)

EDIT Those patterns "any_symbols..." I've mentioned in question are just textual representation of what I'm trying to input. This is not what I type in input field :) Usually I type "[email protected]", or "[email protected]" and etc. :)

EDIT2 Actuall code:

   var email_regex = new RegExp("^.+@.+\..{2,8}$");
if ($target.val().match(email_regex) !== null){
    $button.removeAttr('disabled').removeClass('disabled');
}
else{
    $button.attr('disabled', 'disabled').addClass('disabled');
}

EDIT3 *Found the problem!* It wasn't the regex itself, it was how I passed regex to Regex function... it should be

 new RegExp(/^.+@.+\..{2,8}$/);

not the

new RegExp("^.+@.+\..{2,8}$");

As I've said this whole regex thing is quite new to me :))

Upvotes: 2

Views: 87

Answers (3)

Álvaro González
Álvaro González

Reputation: 146640

You need to escape the slash:

'any_symbols@four_symbols'.match('^.+@.+\\..{2,8}$');
                                        ^^

Otherwise, JavaScript reads \. as an unknown escape sequence and ignores the slash:

For characters not listed [...] a preceding backslash is ignored, but this usage is deprecated and should be avoided.

(Damn, this was hard to spot...)

Upvotes: 1

lu1s
lu1s

Reputation: 5831

Suposely the regex for a real email address is not quite simple, since it should comply with an RFC standard.

However, if this works for you, I've used it with no problems:

// The regex: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/

// To test it:
var regex = new RegExp(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/);

if( regex.test( your_string ) ){ ... } // returns true if valid

If you really need to accept ANY symbols, you can use the regex that Birei posted.

Upvotes: 1

Birei
Birei

Reputation: 36282

Not a Javascript expert, but with your definition of any_symbols@any_symbols.two_to_eight_symbols I think this could work:

^[^@]+@[^.]+\..{2,8}$

Upvotes: 1

Related Questions