Page 1 of 1

JavaScript Regex

Posted: Sat Feb 04, 2006 9:36 am
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.

Posted: Sat Feb 04, 2006 11:16 am
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.

Posted: Sat Feb 04, 2006 12:28 pm
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 =/

Posted: Sat Feb 04, 2006 9:27 pm
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