VirtualMV/JavaScript/Case Study: Forms/Validation Detail

From WikiEducator
Jump to: navigation, search



Adding Validation Code

Now we have the rudiments of the validation code sorted, and a way to de-bug, it is time to complete the validation picture.

At this point I'm going to introduce a tricky check box switch that will be checked if the form is ok (or remain off if there is an error)

DVD Rentals form showing error and validation check box


In the html file I will add

<input type="checkbox" name="chkFormOk" />

Now for some pseudo-code (before I show you the js code)

  • When CheckData is run turn ON chkFormOk
  • If any error is found turn it OFF

So the code will look like ..

function fnCheckOK(strName) {
  strName.style.background = "#FFFFFF";
  if((strName.value=="")||!isNaN(strName.value)) {
    strName.style.background = "#FBEC5D";
	document.myForm.chkFormOk.checked = false;
    return false}
  else {return true}
}
  function fnCheckData() {
// Set checked field 
 document.myForm.chkFormOk.checked = true;
// Check Name, Address & Phone
	fnCheckOK(document.myForm.txtFullName);
	fnCheckOK(document.myForm.txtAdd);
	fnCheckOK(document.myForm.txtPhone);
}

Note that I have fnCheckOK before fnCheckData, following this will make your code easier to read.

In a final version of the code you would make the check box invisible, but its useful to see it while you are programming and checking your code.

It can also be useful when a lot of validation is being done, to provide an error message hint on the form. You can create a div area and add to the .innerHTML as each error is encountered.

VmvIcon References.png References

virtualMV  |  Superquick wiki guide  |  Please give me some feedback

VirtualMV/JavaScript/Case Study: Forms/Validation Detail. (2017). In WikiEducator/VirtualMV wiki. Retrieved October 21, 2017, from http://wikieducator.org/VirtualMV/JavaScript/Case_Study:_Forms/Validation_Detail    (zotero)