Jump to content

Should this regular expression work in PHP and Javascript?


henryhenry

Recommended Posts

Here is my reg exp:^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$It is for checking emails. I have taken from the site http://regexlib.com - thanks!Oddly enough in javascript, the following validates: henry@henry ... But in PHP it doesn't.I'm thinking - 1. my reg exp is wrong (shouldn't) 2. my javascript is dodgy 3. my php is dodgy 4. php and javascript handle reg exp differently?Any ideas?ie - here's my php:

 $rule= '"^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$"'; if (!preg_match($rule, stripslashes(trim($a_email[$i]))))    { $a_errors[]= 'The email address entered is not valid.'; } else    { $v_email[$i]= escape_data($a_email[$i]); }

and here's my java script:

 var filterEmail= new RegExp("^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$"); if (filterEmail.test(inputValue))   { window.formValidity[instance]='valid'; } else   { window.formValidity[instance]='invalid'; }

Thanks as ever!Henry

Link to comment
Share on other sites

Hi!You need to add slashes (/) to the start and end of the pattern (using PERL-style reg.exp):

$rule= '/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)*\.([a-zA-Z]{2,6})$/';

Hope that Heped...Good Luck and Don't Panic!

Link to comment
Share on other sites

Hi Mr ChisolThanks for the prompt. The solution was something like that...I had been fiddling with the php rule and the slashes went at some point although I think I had them before! I put them back first...In my javascript I was using the test method but I found that setting the reg ex as a string and using match worked properly (using the slashes on the string) while the test method was still letting through x@y.I really don't like javascript!!!

Link to comment
Share on other sites

Just to clarify, you don't necessarily need to use slashes, you can use any character. In fact, the original pattern should have worked because it was using a double-quote as a delimiter. The regexp engine should automatically detect which character you are using for delimiters, people commonly use slashes because of the Perl convention. But you can use any character you want, it's best to choose one that you are not going to use in the pattern. For patterns that match HTML, for example, which have a lot of closing tags like </..>, you would have to escape every slash if you used that as the delimiter, so it would probably make more sense to use something like # or @. It just depends on the situation.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...