One of the most capable AJAX toolkits available is Dojo, in addition to some excellent core technology the toolkit offers an assortment of handy widgets in the Dijit library. While I have enjoyed using Dojo despite some of the rather painful upgrade tracks, I have found the form validation invariably needs to be updated.Dojo provides real-time validation of your form elements based on complex regular expressions. For example, the following field could be used for email and would be appropriately validated:

<input type="text" name="Email" id="Email" value=""
       maxlength="100" style="width: 270px;"
       regExp= "^[a-zA-Z0-9]*\@([a-zA-Z0-9])*\.([a-zA-Z0-9\.])+$"
       invalidMessage="Invalid Email.">

As soon as the user attempts to leave the email input field, the expression defined by regExp is executed and compared against the contents of the text box. In fact, as you type the validation can run interactively and warn you as soon as the field is incorrect.

Editing a form with Dojo field validation using Dijit library

Unfortunately, when the user attempts to submit the form the same magic does not take place. In this case a little JavaScript can be easily used to verify the fields on your form. Here is the long version of that:

function isValid()

	var result = true;

	// security_code
	var fSec = dijit.byId("EMail");
	if (!fSec.isValid())
		result = false;

	return result;


So if the Email field is invalid then this script returns false. A slight modification to your form submission can be used to activate this function automatically before the form submits from the client:

<form method="post" action="my.php" onSubmit="return isValid();">

In the event that fields fail validation, the form post will never be executed from the browser. Note that this is not a substitution for good server-side validation, you should always keep in mind that some rogue users may circumvent JavaScript or could possible be talking to your website with another tool.

As an enhancement to this, use an array to define a set of fields that you want to validate before allowing the submission. This would look something like this:

var flds = [["Email"], ["Phone"], ["Fax"]];

Update the sample block above to read the name of the corresponding field from the flds array and then perform the standard Dijit isValid() operation on them.

Next time I’ll take a look at enhancing the Dojo field validation so that you can turn this off until a form submission has been requested. This will let your users browse through a complex form and complete sections as they are able without field level errors popping up everywhere.

Categories: Technology