Reputation: 57
I'm working on a class project and I am wondering if anyone can provide some input/info as to how I would go about to validating my form fields in a better way. Specifically, I want the alert box to pop up to show all of the missing required fields instead of one box per missing field. Any input would be swell.
<script type="text/Javascript">
function validateForm(assignmentForm)
{
valid = true
if (document.assignmentForm.firstName.value=="")
{
alert ("Please fill in your first name.");
valid = false;
}
if (document.assignmentForm.lastName.value=="")
{
alert ("Please fill in your last name.");
valid = false;
}
return valid;
}
</script>
I'm new to using javascript within HTML so I apologize in advance for what is most likely a very newbie question. Also, here's a snippet of the HTML portion:
<!--Name Text Fields-->
<form id="assignmentForm" name="assignmentForm" method="post" onsubmit="return validateForm();">
<table cellspacing="15">
<tr>
<td><a href="#">First Name: </a></td>
<td><input type="text" id="firstName" name="firstName"></td>
</tr>
<tr>
<td><a href="#">Last Name: </a></td>
<td><input type="text" id="lastName" name="lastName"></td>
</tr>
Upvotes: 1
Views: 16207
Reputation: 781028
Have each validation step add its message to an array that you display after all validations are done.
function validateForm(assignmentForm)
{
var messages = [];
if (document.assignmentForm.firstName.value=="")
{
messages.push("Please fill in your first name.");
}
if (document.assignmentForm.lastName.value=="")
{
messages.push("Please fill in your last name.");
}
if (messages.length > 0) {
alert(messages.join('\n'));
return false;
} else {
return true;
}
}
Upvotes: 4
Reputation: 2548
If you create a string variable in the function before checking each field, you can then append a notification about which needs to be filled in.
After all checks have been completed, then show the alert using the string you have built.
I would also suggest that you check fields for valid data as well - this may not be necessary for the class work you are doing right now, but it is good practice for any real world code. For example, make sure that name is made of only characters.
Upvotes: 0