View Full Version : Simple Required Form Filed Question

01-27-2009, 10:54 PM
Hi all, I am new to Javascript and was seeking out help to a page I am going to try and build. I am creating a form with 2 text boxes, and I want to be able to validate and make sure that if either 1 has data inside, to check the other to make sure that it must have data as well, and error out if not. I found this code online, any help with making it the way I want it would be fantastic. Thanks much in advance.

function verify() {
var themessage = "You are required to complete the following fields: ";
if (document.form.first.value!="") {
themessage = themessage + " - First Name";
if (document.form.last.value=="") {
themessage = themessage + " - Last Name";

//alert if fields are empty and cancel form submit
if (themessage == "You are required to complete the following fields: ") {
else {
return false;

<form name=form method="post" action="">
<input type=text name="first" size="20"> First Name<BR>
<input type=text name="last" size="20"> Last Name<BR>
<input type=button value="Submit Request" onclick="verify();">
<input type=reset value="Clear Form"><br>

I am sure this is an easy fix, but like I said, I am new to js and any help would be greatly appreciated.

Thanks much!


01-27-2009, 11:32 PM
What's the problem with this code? How is it not what you wanted?

01-27-2009, 11:38 PM
It only tests for 1...not the other way around...essentially if first wasnt empty make sure that b DOES have data, or error... and vice versa if B DOES have data make sure A has data or error as well.

Philip M
01-28-2009, 01:40 PM
A simple correction:-

if (document.form.first.value == "") {

But this "validation" is hardly worthy of the name, as any character, even a single space or a ?, will pass the validation test.

At a minimum you should use something like:-

var fn = document.form.first.value;
fn = fn.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
if (/[^a-z]/gi.test(fn) || fn.length <2) { // must be A-Za-z only, min 2 characters
themessage = themessage + " - First Name";

var ln = document.form.last.value;
ln = ln.replace(/^\s+|\s+$/g,""); // strip leading and trailing spaces
if (/[^a-z\-\']/gi.test(ln) || ln.length <3) { // must be A-Za-z or hyphen or apostrophe only, min 3 characters
themessage = themessage + " - Last Name";

BTW, the time to say "thanks" is afterwards, not beforehand which gives the impression that you take other people's unpaid assistance for granted. Or as British politician Neil Kinnock put it, "Don't belch before you have had the meal." Prefer to use "please" beforehand and if you find a response helpful then you can use the "Thank User For This Post" button.

Quizmaster: What is the English translation of the French word voiture?
Contestant: A tree.