VirtualMV/JavaScript/Case Study: Forms/Validation Detail
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)
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.
References
virtualMV | Superquick wiki guide | Please give me some feedback |
VirtualMV/JavaScript/Case Study: Forms/Validation Detail. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 5, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/Case_Study:_Forms/Validation_Detail (zotero)
|