If you are not using jQuery, I will just write a validation method that you can fire when submitting the form. The method can check text fields to make sure they are not empty or the default value. The method will return bool, and if it is false, you can turn off your warning and assign classes to highlight fields that have not passed validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)"> <input type="text" name="name" value="Name"/><br /> <input type="text" name="addressLine01" value="Address Line 1"/><br /> <input type="submit"/> </form>
JavaScript:
function validateForm(form) { var nameField = form.name; var addressLine01 = form.addressLine01; if (isNotEmpty(nameField)) { if(isNotEmpty(addressLine01)) { return true; { { return false; } function isNotEmpty(field) { var fieldData = field.value; if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) { field.className = "FieldError"; //Classs to highlight error alert("Please correct the errors in order to continue."); return false; } else { field.className = "FieldOk"; //Resets field back to default return true; //Submits form } }
The validateForm method assigns the elements you want to check, and then in this case calls the isNotEmpty method to check whether the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns true or if the condition is not met for this field, it will return false.
Give this snapshot and let me know if this helps or if you have any questions. Of course, you can write additional custom methods to check only the number, email address, valid URL, etc.
If you use jQuery at all, I would try checking out the jQuery Validation plugin. I use it for my last few projects, and that is pretty good. Check it out if you have a chance. http://docs.jquery.com/Plugins/Validation
source share