JavaScript Regex

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

JavaScript Regex

Post by s.dot »

Is regex in javascript any different than regex anywhere else?

Code: Select all

// check that email appears to be valid
if(!document.register.email.value.match(/^(.+)@(.+)\\.(.+)$/)){
	alert('Please enter a valid email address.');
	return false;
}
That regex is the same that I use in my PHP codes to check email addresses. But no matter what I put into the form I always get the alert.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

.+ is greedy... use .*? instead. It's always matching because it essentially will match *anything*.

JavaScript regex is PCRE for the most part but it doesn't meet the same standards as Perl or PHP do.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Code: Select all

// check that email appears to be valid 
if(!document.register.email.value.match(/^(.*?)@(.*?)\\.(.*?)$/)){ 
   alert('Please enter a valid email address.'); 
   return false; 
}
This still accepts anything also.

When using other regexes I found that using \w instead of [a-z0-9_] works and the group of valid characters doesn't.

so maybe I need something like /^(\w+)@(\w+)$/

I dunno =/
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

The dot after the @ has two backslashes before it. This isn;t needed when you're not inside a string. It's reading as literal slash fllowed by any character.

Apart from this that regex should work for any address of the form name@zone.tld
Post Reply