The simplest field validation is to test a text input field to see if something has been entered into it. All that you need to do is to compare the field with an empty string like this:
if (fld == '') alert('Please enter something, this field is mandatory');
}
The problem with this is that it doesn't check that what has been entered into the field is meaningful. Simply entering a single space into the field will pass this validation.
You will also have problems with your subsequent validations of the field to check that the actual content of the field is realistic for the type of input that you are expecting if your visitors enter spaces either before or after the actual field content.
We can solve this problem and make our mandatory field test more useful at the same time by removing any leading and trailing blanks from the field before we test the field. If all that is entered is blanks then they will all be removed leaving the field empty again. The following function will do this for us:
function stripBlanks(fld) {
var result = "";
var c = 0;
for (i=0; i<fld.length; i++) {
if (fld.charAt(i) != " " || c > 0) {
result += fld.charAt(i);
if (fld.charAt(i) != " ") c = result.length;
}
}
return result.substr(0,c);
}
So now we can create a function to test our field contains something other than just blanks as follows:
function validField(fld) {
fld = stripBlanks(fld);
if (fld == '') return false;
// other validations for this field to be added here
return true;
}
If we create a function like this for each of the fields on our form (giving each function an appropriate name) then we can validate the field at the time something is entered into it by adding onblur="if (!validField(this.value)) alert('Entry Invalid');" to the field input tag. If the field isn't mandatory then we can leave out the compare with the empty string and the function will still be useful to use to perform any other validations that we need to perform on the field. The same validField function can also be called as part of the overall validation that is performed before the entire form is submitted.
Creating these functions will also make it easier to add further validations relevant to the specific field as whatever code you need to perform that validation can be added into the function at the spot indicated and this will also then be performed both when the field has been entered and before the form is submitted.