...

View Full Version : Either/Or Form Validation Help for Beginner



edwin2213
10-02-2012, 01:52 AM
Hello,

I am very new to JavaScript and am having trouble getting my form to validate the entries the way I want. I am trying to get the form to require an email address or street address. Both are OK but neither is not OK. I have been able to get it to work if I require everything. Here is what I was able to come up with. Any help would be greatly appreciated.

Thank you,
David


function validateForm()
{
var fn=document.forms["Form"]["firstname"].value;
if (fn==null || fn=="")
{
alert("First Name must be filled out");
return false;
}
var ln=document.forms["Form"]["lastname"].value;
if (ln==null || ln=="")
{
alert("Last Name must be filled out");
return false;
}
var sa=document.forms["Form"]["streetaddress"].value;
if (sa==null || sa=="")
{
alert("Street Address must be filled out");
return false;
}

var em=document.forms["Form"]["email"].value;
var atpos=em.indexOf("@");
var dotpos=em.lastIndexOf(".");

if (atpos<1 || dotpos<atpos+2 || dotpos+2>=em.length)
{
alert("Email Address not valid.");
return false;
}
}

Old Pedant
10-02-2012, 02:22 AM
(1) Apparently, you gave your <form> a name of "Form". Named forms are obsolete. You should give them id's instead of names. Or you can omit both if...

(2) If you code that form thus:


<form action="...." method="post" onsubmit="return validateForm(this);" >


(3) Form field values are *NEVER* null. If the form field exists, at all, then the value can't be null.

(4) Testing for a non-blank form field is not worth the time or effort. It means that a user can enter a SINGLE SPACE and you will accept it as valid.

(5) Your test for a valid email address is so weak it's not worth bothering with, either.

(6) You really should NOT be using alert() for give error messages, but we'll let that go for now.



// This code assumes you pass in this in the <form> tag
function validateForm(form)
{
// ensure there are at least 2 non-space characters in the names
var fn = form.firstname.value.replace(/\s/g,"");
if ( fn.length < 3 )
{
alert("First Name must be filled out");
return false;
}
var ln = form.lastname.value.replace(/\s/g,"");
if ( ln.length < 3 )
{
alert("Last Name must be filled out");
return false;
}
// and at least 8 characters in the street address? (change min length to suit)
var sa = form.streetaddress.value.replace(/\s/g,"");
if ( se.length > 7 ) return true;

var emre = /^\w[\w\-\'\$\.]+\@([\w\-\'\$]+\.)+[a-z]{2,6}$/i; // this could be better
var trim = /(^\s+|\s+$)/;

var em = form.email.value.replace(trim,"");
if ( emre.test( em ) ) return true;

alert("Neither street address nor valid email address given");
return false;
}

edwin2213
10-02-2012, 03:06 AM
Thank you so much for the help. I am very new to JavaScript so the suggestions/notes are very helpful. I am confused about two things.
1. what do the var emre and var trim mean?
2. does the new code go on a standalone JS page or is it inserted into the HTML?

My forms HTML is(the inline CSS is temporary):


<form style="background-color:#000000; color:#CCCCCC; position:fixed;" name="Form" onSubmit="return validateForm();" method="get" action="Complete.html">
<p>Please complete the following form to sign up for our newsletter.</p><br>
First Name: <input id="firstname" type="text" name="firstname"> <br>
<br>
Last Name: <input id="lastname" type="text" name="lastname"><br>
<br>
Street Address: <input id="streetaddress" type="text" name="streetaddress"><br>
or<br>
Email Address: <input id="emailaddress"type="email" name="email"><br>
<br>
Phone Number: (optional) <input id="phonenumber" type="text" name="phone"><br>
<br>
<input type="submit" value="Submit">
</form>

Thank you for the help and sorry if these questions are stupid. The book I am using to learn this seems to be a little dated. Do you have any recommendations of books/sites for learning JavaScript? I have looked on google, etc but I'm not sure which are good and which aren't.

Thank you,
David

Logic Ali
10-02-2012, 03:15 AM
if ( se.length > 7 ) return true;

The intermediate return statement strikes again.

You can't return true if there are more tests to perform.

Old Pedant
10-02-2012, 03:18 AM
(1) The variables emre and trim are variables that are holding REGULAR EXPRESSIONS. You can look up what that means, but for now just use them and be happy.

(2) You can put the JS either in the HTML page or in a separate JS file. Makes no difference.

You will need to change your <form> tag, thus:


<form style="background-color:#000000; color:#CCCCCC; position:fixed;"
onsubmit="return validateForm(this);" method="get" action="Complete.html">

(You don't have to get rid of the name of the <form>, but it serves no purpose once you pass the reference to the <form> into the function using the this keyword.)

There are some "sticky" threads at the head of this JavaScript forum with references to sites to look at.

*************

As an aside: There really is no reason to give your <form> fields ids as well as names. No place in your code do you even use or need the ids. Note that a form field WITHOUT a name will *NOT* be sent on to the next page as part of the form submittal. So name are needed for the form submittal; id's are not, at all.

Having just said the above, there are a few circumstances where form field id's can come in handy, but you haven't encountered them yet and likely won't for a while.

Old Pedant
10-02-2012, 03:20 AM
The intermediate return statement strikes again.

You can't return true if there are more tests to perform.

WRONG.

Read his requirements. He WANTS to accept EITHER a street address OR an email address as sufficient.

So my code is simply saying "if you get a street address, there is no need to then check the email address."

Would this trick work if there were *OTHER* validations to perform, AFTER the street address and email checks? Of course not. But that's exactly why I placed those two checks last.

Logic Ali
10-02-2012, 04:10 AM
WRONG.

Read his requirements. He WANTS to accept EITHER a street address OR an email address as sufficient.

So my code is simply saying "if you get a street address, there is no need to then check the email address."

In that case the solution should make the intention unambiguously clear, and splattering return statements everywhere isn't going to do that.


function validateForm(form)
{
// ensure there are at least 2 non-space characters in the names
var fn = form.firstname.value.replace(/\s/g,""),
ok = true;

if ( fn.length < 3 )
{
alert("First Name must be filled out");
ok = false;
}
var ln = form.lastname.value.replace(/\s/g,"");

if ( ok && ln.length < 3 )
{
alert("Last Name must be filled out");
ok = false;
}

// and at least 8 characters in the street address? (change min length to suit)

if( ok )
{
var sa = form.streetaddress.value.replace(/\s/g,"");

var emre = /^\w[\w\-\'\$\.]+\@([\w\-\'\$]+\.)+[a-z]{2,6}$/i; // this could be better
var trim = /(^\s+|\s+$)/;

var em = form.email.value.replace(trim,"");

ok = emre.test( em ) || se.length > 7;

if( !ok )
alert("Neither street address nor valid email address given");
}

return ok;
}

Old Pedant
10-02-2012, 08:51 PM
If you want a *good* solution, then you shouldn't be using alert( ) ... which I already mentioned. This is clearly a thread about a newbie first doing validation. I gave a working solution for this simple case. If you want really GOOD validation, it shouldn't be done this way in any case.

Your validation is horribly faulty, to me, in that you will only show the first error message and not all validation errors. In that, you share the coding with the original. But that still doesn't make it good validation.

Finally, if you are (as you seem to be) one of those purists who believe that functions should never return early, then I have nothing more to say. We will never agree.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum