Client-side Form Validation

Every form needs to be validated in one way or another. The most basic form of validation is check that all required fields have been given values. Here is a script that should help with that.

Firstly, let's update the form fields that are mandatory. We will apply a class to those fields called mandatory.

<form id="frmfeedback" action="add.asp" method="post">
	<label>Summary</label>
	<input class="feature mandatory" type="text" id="title" name="title" />

	<label>Description</label>
	<textarea class="feature mandatory" rows="3" id="description" name="description"></textarea>

	<label>How you found us</label>
	<select id="source" class="combo">
	<option value="Google">Google</option>
	<option value="Word of Mouth">Word of Mouth</option>
	<option value="TV">Television</option>	
	</select>
	
	<input type="button" id="save-request" value="Save" />
</form>

You can see that we have two elements that are mandatory and one that is not. Easy so far.

Our workflow will be:

  • When the Save button clicked, check that all mandatory fields have values
    • If not
      • Mark all the missing fields as requiring attention
      • Set the focus in the first element
    • If so
      • Post the form

This is the javascript code that you need to put in the bottom of your page to do this:

$("#save-request").click(function () {
    var validationpasses = true;
    $(".mandatory").each(function () {
        if ($(this).val() == "") {
            $(this).addClass("error").focus();
            validationpasses = false;
        };
    })

    if (!validationpasses) {
        $(".mandatory.error").first().focus();
    } else {
        frmfeedback.submit();
    }
});

So, the system is looping through all the fields that are marked as mandatory and checking if they have values. If they do not, a class is being applied to that element which distinguishes it as needing attention. Then the system puts the cursor in the first of these elements awaiting use intervention. If all the fields have been filled in, the form is submitted.

PS I love the chaining in $(".mandatory.error").first().focus();. JQuery is so cool as this.

Til next time...