Forum Moderators: open

Message Too Old, No Replies

javascript form validation

need some help

         

benji

4:29 pm on Sep 19, 2008 (gmt 0)

10+ Year Member



I'm new to javascript, and stuck on this one:
I have a form, where I want to validate that the email field is either blank, or a vaild email address.

I already have a email regular expression.

The code I though would work is this:

if(!email == "" ¦¦ !email.match(email.RegExp)) {
alert ("alert message here");
return false;
{

and so on...
I have already set a variable for "email" etc. I just can't get the bit to work for it either being blank or matching the regular expression!

maximillianos

4:49 pm on Sep 20, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well you are saying here "if not" equal to blank. Aren't you trying to check if it IS blank ? Get rid of the not sign (!).

benji

11:02 am on Sep 21, 2008 (gmt 0)

10+ Year Member



Thanks for the reply, but the "if not" part is what I want....
"if not" blank, or "if not" match regex, return false.
I wish for the field to be either blank, or a valid email address.

phranque

11:50 am on Sep 21, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



welcome to WebmasterWorld [webmasterworld.com], benji!

have you tried printing out the length of the email value and/or the email value itself (between delimiters) to insure there are no "extra" characters?

Fotiman

8:31 pm on Sep 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



!email.match(email.RegExp)

Is "email" a String? If so, then what is email.RegExp? Do you have two variables both named email?

daveVk

3:03 am on Sep 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think you want

if(!((email == "" )¦¦(email.match(email.RegExp))))

rather than

if(!email == "" ¦¦ !email.match(email.RegExp))

not ( A or B ) is different from ( not A ) or ( not B ) demoran theory

Better still is to avoid mixing OR's and NOT's

if ( (email == "" ) ¦¦ (email.match(email.RegExp)) ) {
// ok code if any
} else {
alert ("alert message here");
return false;
}

benji

8:52 am on Sep 22, 2008 (gmt 0)

10+ Year Member



Thankyou very much - it looks as though the last tip has cracked it :)