Tech Musings

Sunday, November 27, 2005

Javascript form validation examples

I use javascript form validation quite a bit to ensure users are submitting the correct stuff into my MySQL tables.

"confirm" will deliver a warning prior to submission, while "alert" can force a user to go back and correct something.

function check() { //example of how to validate a checkbox in a form
if(document.form2.object_overwrite.checked == false && document.form1.userfile.value != "")
{ alert('Did you forget to check the overwrite box?');
return false;
}

UPDATE! 2-3-07!! Don't forget to add the word return in the onClick or onSubmit event!!!

function check2() { //example of check on whether or not text has been entered in a text box.
if(document.form2.docs_path.value != "" && document.form2.userfile.value != "")
{ alert('You can\'t enter a Web site address and upload a file at the same time. Please try again.');
return false;} //next is an example of validating a radio button combined with text box.
if(document.form2.choice[0].checked && document.form2.docs_path.value == "")
{ alert('You chose to add a Web address but the field appears to be empty. Please try again.');
return false;}
if(document.form2.choice[1].checked && document.form2.userfile.value == "")
{ alert('You chose to add upload a file but the document upload field appears to be empty. Please try again.');
return false;}
if(document.form2.choice[2].checked && (document.form2.docs_path.value != "" || document.form2.userfile.value != ""))
{ alert('You chose to provide no evidence, yet a path to evidence appears in one of the upload fields. Please resolve this conflict.');
return false;}
if(document.form2.docs_path.value == "" && document.form2.userfile.value == "")
{ confirm('You have chosen to not provide evidence for this standard. Is this okay?');
}
return true;
}

<-form method="post" name="form2" onsubmit="return check();" OR "return check2();">

Example can be seen on a.php in Pt. Loma e-portfolio page.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home