...

View Full Version : RegExp



webguy08
04-25-2010, 02:50 PM
Hi all,

I am having trouble understanding how to get RegExp to work. I've read so many tutorials but none have been clear. They all just explain the patterns you can check for but not how to piece them together! I am trying to write a RegExp pattern that checks an email address so that it allows the characters a-zA-z0-9_ before and after the @

How would I go about doing this?
I tried


new RegExp("[a-zA-z0-9_].+@[a-zA-z0-9_].+");

but that didnt work.

I appreciate any help :thumbsup:

Philip M
04-25-2010, 03:50 PM
You can collapse a-zA-Z0-9_ into \w.


<script type = "text/javascript">
var reg = /^\w+@\w+\.\w{2,6}$/;

// OR var reg = new RegExp("^\\w+@\\w+\\.\\w{2,6}$"); // note in this syntax that the \ must be escaped with another \

if (reg.test("me@mydomain.com")) {
alert("foo!");
}
else {
alert ("bar!")
}
</script>But that is not really a satisfactory email validation - it would pass 999@888.777. Try this:-


if (!(/^([a-z0-9])(([\-.]|[_]+)?([a-z0-9]+))*(@)([a-z0-9])((([a-z0-9\-\.]+))?)*((.[a-z]{2,3})?(.[a-z]{2,6}))$/i.test(email.value))) { // email, no two consecutive dots, returns true if address is invalid.


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

webguy08
04-25-2010, 06:34 PM
I began by testing:


new RegExp("\\w+@\\w+");

but I could still pass in @@@ :confused:

Philip M
04-25-2010, 06:47 PM
new RegExp("\\w+@\\w+"); will pass multiple @ signs such as me@mydoma@in.com (but not me@@@mydomain.com) because the pattern is in fact matched by e@m (and indeed by a@i). However, the regexes I gave you are not quite correct as I forgot the ^ and $ signs (start and end of string, i.e. nothing in the string but the regex to match. ). I have amended Post #2 accordingly.

var reg = new RegExp("^\\w+@\\w+$");
will not pass @@@ (multiple @ signs)

webguy08
04-25-2010, 08:52 PM
new RegExp("\\w+@\\w+"); will pass multiple @ signs such as me@mydoma@in.com (but not me@@@mydomain.com) because the pattern is in fact matched by e@m (and indeed by a@i).

I think I understand it, however, I changed my code to new RegExp("^\\w+@\\w+$"); and then tried entering @@@ and it still passed the test(...) function. I tried entering ;@; and even that didn't come out as false! I don't understand why my code isn't working. It only complains if there is no @ sign and nothing before and after it, ie. ".+@.+"

Philip M
04-25-2010, 08:56 PM
Well, it works for me. :)


<script type = "text/javascript">
var reg = new RegExp("^\\w+@\\w+$");
if (reg.test("me@@@mydomain")) {
alert ("foo!"); // true
}
else {
alert ("bar!"); // false
}
</script>

webguy08
04-26-2010, 02:35 PM
Turns out it wasn't updating the JS file...:rolleyes: Works now.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum