Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: JavaScript
Expertise: Beginner
Oct 19, 2000

Form Validation

Question:
I need to perform a validation on five fields in a form. The logic is:

If field1 length >0 then disallow form submission if field2, field3, field4, and field5 are all empty. However, if any one of the fields (2-5) contain info, then submit the form.

I have tried many variations of the following code, but it still forces me to enter something in all the fields (2-5).

if ((document.addorupdate.field1.value.length >1) && 
((document.addorupdate.field2.value == "")| | 
(document.addorupdate.field3.value == "")| |
(document.addorupdate.field4.value == "")| |
(document.addorupdate.field5.value == ""))){
alert("Sorry, you must update one of the empty fields.");
return false;
}
else {return true ;}

Answer:
Try this instead:

myForm = document.addorupdate
filledOut = false

if (myForm.field1.value != "") {
	if (myForm.field2.value != "") filledOut = true
	if (myForm.field3.value != "") filledOut = true
	if (myForm.field4.value != "") filledOut = true
	if (myForm.field5.value != "") filledOut = true
}

if !(filledOut)
	alert("Sorry, you must update one of the empty fields.")

return filledOut
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date