DHTML Form Enhancement - Regex Validation and Equality Checking
(Page 4 of 5 )
The two uses of the function on the provious page discussed here cover two of the most comon applications of a form - checking for proper data format (zip code, email address, phone number, etc) and confirmation of data entered in a field by repeating the entry (password confirmation, email address confirmation, etc). To test a field's value against a regular expression, use the following:
<input validate="regex" regex="\b\w+@(\w+\.)+\w{2,3}\b" name="emailAddress" size="35" maxlength="40" />
Here is a simple email address validation check. We can further improve this example by forcing the user to retype their address and verify that they entered the same address in the confirmation field:
<input validate="equals" equals="emailAddress" name="confirmEmailAddress" size="35" maxlength="50" />
These two fields will provide two forms of validation: first, it will ensure that the user enters a proper email address in the email address field; second, it will ensure that the user retypes their address in the confirmation field correctly. Finally we can add the failure attribute to allow the form to provide the user with a custom error message, rather than have the form give the default error messages for validation failure. For example:
<input validate="regex" regex="\b\w+@(\w+\.)+\w{2,3}\b" name="emailAddress" failure="The email address you entered is not valid." size="35" maxlength="40" />
<input validate="equals" equals="emailAddress" name="confirmEmailAddress" failure="You must confirm your email address correctly." size="35" maxlength="50" />
XHTML Validation purists may be saying at this point "wait - my form will not be W3C compliant with your custom attributes in place". True, the current validator will reject your page and say that the XHTML Markup is not compliant. This will not be true in the future, however. After all, the X in XHTML stands for eXtensible, meaning that within certain guidelines, the basic markup can be extended to suit the needs of a particular application. It is also worth noting here that, if you did not see in the example code, when a field fails validation, the function halts validating the form and focuses on the field that failed.
Next: Extending the validate function >>
More HTML Articles
More By David Fells