...

View Full Version : Validating Form Data Using An Array



chelseasikoebs
12-05-2012, 06:42 PM
I have been racking my brain for at least 6 hours trying different things and researching and trying to figure out why this won't work! It seems logical to me, but obviously I'm missing something. I just need for it to pop up an alert box if any field is left blank. It is supposed to use a loop to check all the fields using an array (elements). The form isn't actually supposed to submit any info at this point so a method, etc. isn't needed.

Here's my code:


<html>
<head>
<title>Smallmart Not-So-Supercenter Free Offer Form</title>
<link rel="stylesheet" type="text/css" href="smallmart.css" />
<script type="text/javascript">
<!--

var fullName = document.getElementById("fullName").value;
var address = document.getElementById("address").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var zip = document.getElementById("zip").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;

var elements = [fullName, address, city, state, zip, phone, email];
var i = 1;

function validate()
{
if(elements[i].length == 0)
{
alert("All fields must have data.");
return false;
i++;
}

else
{
alert("Thank you!");
return true;
}

}

// -->
</script>

</head>

<body>

<div id="wrapper">
<div id="masthead">
<img src="Small-mart.jpg" alt="Smallmart">
</div>

<div id="nav">
<a href="index.html" class="unSelectedPg">Home</a>
<a href="offer.html" class="unSelectedPg">Free Offer!</a>
<span class="selectedPg">Order Now</span>
</div>

<div id="header">
Smallmart Not-So-Supercenter Free Offer Form
</div>

<div id="content">
<form>
Full Name: <input type="text" id="fullName" name="fullName" onblur="validate(this)">
<br />
Street Address: <input type="text" id="address" name="address" onblur="validate(this)">
<br />
City: <input type="text" id="city" name="city" onblur="validate(this)">
<br />
State:
<select name="state" id="state" onblur="validate(this)">
<option value="">
<option value="AL">Alabama
<option value="AK">Alaska
<option value="AZ">Arizona
<option value="AR">Arkansas
<option value="CA">California
<option value="CO">Colorado
</select><br />
Zip Code: <input type="text" id="zip" name="zip" onblur="validate(this)">
<br />
Phone Number: <input type="text" id="phone" name="phone" onblur="validate(this)">
<br />
Email Address: <input type="text" id="email" name="email" onblur="validate(this)">
<br />
<input type="button" id="submit" name="submit" value="Submit" class="submit">
</form>
</div>
</div>
</body>
</html>

Philip M
12-05-2012, 07:00 PM
You are trying to capture the value of the form elements before they have been filled in! Your script will run onload. You must include the first ten lines within your function.

var fullName = document.getElementById("fullName").value;

You are using the same name(s) for an HTML element and a Javascript global variable.

var i = 1;
The index of an array starts at 0.

You need to loop through the values to check if any are blank. As it is you test only if(elements[i].length == 0) where i = 1 (= address).

BUT.....

Form validation of the pattern if (document.formname.formfield.value.length == 0) - that is blank - is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. A proper name may only contain letters, hyphen, space and apostrophe.
Numeric values, such as zip codes and phone numbers, should be validated as such. Ditto email addresses. This topic has been covered many times before in this forum.

The <!-- and //--> comment (hiding) tags have not been necessary since IE3 (i.e. since September 1997). If you see these in some published script it is a warning that you are looking at ancient and perhaps unreliable code.



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

chelseasikoebs
12-05-2012, 07:08 PM
Philip, thank you! I am just learning JavaScript. Have never used it before. I didn't realize HTML elements and JS variables had to have different names. I thought they could be the same to make it easier to read. So, good to know!

Also, I know that usually i should be set to 0, but it seems so much easier to follow if you start it at 1 instead which is why I did that. Does it break the code to initialize it that way?

chelseasikoebs
12-05-2012, 07:10 PM
if(elements[i].length == 0)
Form validation of the pattern if (document.formname.formfield.value.length == 0) - that is blank - is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. A proper name may only contain letters, hyphen, space and apostrophe.
Numeric values, such as zip codes and phone numbers, should be validated as such. Ditto email addresses.

I don't know if it's because I'm so new to JS, but I'm not following this. My JavaScript book shows this format for validating data so that's what I used...

Philip M
12-05-2012, 07:17 PM
I don't know if it's because I'm so new to JS, but I'm not following this.

Well, if you test whether a field is blank, you will allow the user to enter rubbish or even just a single space in each field. That is virtually useless. I would advise you to get a new book!

As I say, it is not at all sufficient to check that each field has a value of some kind. The values entered by the user must make sense! If you ask for a zip code it makes no sense if the user enters "Mickey Mouse". If you ask for a proper name it makes no sense if the user enters 45%()**$$$295. If you ask for a email address it makes no sense if the user enters 1234. OK? I have to say that to validate a form properly involves quite a lot of code.

Strictly only global Javascript varaibles and HTML element names can potentially clash, but it is strongly advised not to use the same identical names in all circumstances.

You are trying to trigger your valiadtion script onblur of each form element. That does not make sense either! The user has had no opportunity to fill in the remaining fields. A select list validation should be activated onchange, not on onblur.

To be quite candid, there are so many problems that I think you should devote a lot more time to studying Javascript (using a better and more up-to-date book than the one you now have) before embarking on this project.

chelseasikoebs
12-05-2012, 07:18 PM
You are using the same name(s) for an HTML element and a Javascript global variable.

var i = 1;
The index of an array starts at 0.

You need to loop through the values to check if any are blank. As it is you test only if(elements[i].length == 0) where i = 1 (= address).

I thought that if you initialize the value of i to 1 then it changes what index number the array starts at, so it would now go 1, 2, 3, 4, 5 instead of 0, 1, 2, 3, 4?

chelseasikoebs
12-05-2012, 07:22 PM
Well, if you test whether a field is blank, you will allow the user to enter rubbish or even just a single space in each field. That is virtually useless. I would advise you to get a new book!

As I say, it is not at all sufficient to check that each field has a value. The values entered by the user must make sense!

Oh... I see what you're saying. But, it may just be because it's a book for beginners and it's taking it one step at a time? I think at this point, we're not concerned with what the person is entering so much as learning how to get the beginning steps of the code written. Maybe?

Philip M
12-05-2012, 07:35 PM
I thought that if you initialize the value of i to 1 then it changes what index number the array starts at, so it would now go 1, 2, 3, 4, 5 instead of 0, 1, 2, 3, 4?

The first element of an array is always index 0.

I think you are confusing this with a loop counter which might very well be

for (var i =1; ....

i.e. the loop counter starts at 1. So a reference to array[i] will be the second element of the array.

Is this homework of some kind?

If so, take it one step at a time. Just have one form field and validate that when the user clicks on Submit. Then add a second field and validate both. OK? I get the impression that you are trying to run before you can walk.

<form id = "myform" onsubmit = "return validate(this.form)">
The validate() function should return true (if no errors) or false. But as I say the validation requires far more than just a check if the field is blank.

chelseasikoebs
12-05-2012, 07:41 PM
The first element of an array is always index 0.

I think you are confusing this with a loop counter which might very well be

for (var i =1; ....

i.e. the loop counter starts at 1.

Is this homework of some kind?

OH! Yes! A counter. That's what i is supposed to be for in my code. I started out using a for statement, but I don't think it was making sense. Yes, it's homework that I cannot figure out and my instructor is never available--it's an online class and he also teaches classes on a campus. I can usually get things figured out, but I'm really stumped on this one. I may have to just turn it in with errors. He'll obviously send my homework back with fixes.

chelseasikoebs
12-05-2012, 07:45 PM
If so, take it one step at a time. Just have one form field and validate that when the user clicks on Submit. Then add a second field and validate both. OK? I get the impression that you are trying to run before you can walk.

Well, I started out using something like


function validate(inputField)
{
if(inputField.value.length == 0)
{
alert(...);
return false;
}
return true;
}

and I got it to work somewhat, but then to try to incorporate an array messed it all up for me.

chelseasikoebs
12-05-2012, 07:49 PM
<form id = "myform" onsubmit = "return validate(this.form)">
The validate() function should return true (if no errors) or false.

Funny, I just changed the form tag in my HTML to
<form name="custInfo" onsubmit="return validate()">

but then I also changed my variables to be
var fullName = document.forms["custInfo"]["custName"].value;
etc. and still not working. I'll do some more finangling. lol

Philip M
12-05-2012, 07:50 PM
Well, I started out using something like


function validate(inputField)
{
if(inputField.value.length == 0)
{
alert(...);
return false;
}
return true;
}

and I got it to work somewhat, but then to try to incorporate an array messed it all up for me.

You could do

<input type = "text" id = "fullName" onblur = "validate(this)">

Philip M
12-05-2012, 07:52 PM
Funny, I just changed the form tag in my HTML to
<form name="custInfo" onsubmit="return validate()">

but then I also changed my variables to be
var fullName = document.forms["custInfo"]["custName"].value;
etc. and still not working. I'll do some more finangling. lol

Assigning a name to a form is deprecated (obsolete). Use an id instead

I see no form element named "custName". Unless you have renamed it as per my advice.

chelseasikoebs
12-05-2012, 07:54 PM
I keep getting an error, "unable to get the property of 'custName': object is null or undefined".

chelseasikoebs
12-05-2012, 07:55 PM
Assigning a name to a form is deprecated (obsolete). Use an id instead

I see no form element named "custName".

Oh. Wow. I got that straight from the w3schools.com site!

Sorry, I changed my HTML elements to have "cust" in front of them so fullName changed to custName, address changed to custAddr, city to custCity, etc.

chelseasikoebs
12-05-2012, 08:04 PM
You could do

<input type = "text" id = "fullName" onblur = "validate(this)">

My input tags look like this per my book:
<input type="text" id="custEmail" name="custEmail" onblur="validate(this);">

Is having both name and id in there messing it up?

chelseasikoebs
12-05-2012, 08:08 PM
My brain's getting fried! lol I may have to submit what I have with questions to my instructor and hope he gets back to me in time to get it figured out and turned in on time on Sunday. Seems like plenty of time, but for some reason online instructors aren't "online" much! ;)

Philip M
12-05-2012, 08:08 PM
Oh. Wow. I got that straight from the w3schools.com site!



You should be aware that the w3schools site is now very much out of date. As felgall says, it teaches 20th century Javascript.


<input type="text" id="custName" name="custName" onblur="validateName(this);">

<script type = "text/javascript">

function validateName (which) {
var val = which.value;
val = val.replace(/[^a-z\s\-]gi, ""); // strip all but letters (ignore case) and hyphens and spaces - Mary-Lou Smith
which.value = val; // write it back to the field
if (val.length < 4) {
alert ("Your name must have at least 4 alpha characters");
which.focus(); // refocus on the incorrect field so compelling the user to make a valid entry
return false;
}
}
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum