- Custom attributes meant the page would not validate correctly as the XHTML would not be semantically correct.
- You couldn't just add the script and an onsubmit handler to any page you wanted to use it on as it also required that any form elements that required validating would also need custom attributes added to them.
Therefore I abandoned this generic route and went down the route of creating local functions appropriate to the page they were located on.
Include a reference to the script in your page which you can download here.
Attach an onsubmit event handler to the form you wish to validate that calls my Validate function passing a reference to the form e.g
To configure how each form element is validated you add one of the following class names to the element.
TextInput, NumericInput, IntegerInput, DateInput, EmailInput, URLInput, PostCodeInput, PhoneInput
e.g <input type="text" class="TextInput" id="txtName" />
To make a required field so that the element has to have a value supplied you add an extra class name "Required" to the end of any existing classes.
e.g <input type="text" class="TextInput Required" id="txtName" />
The title of the control that appears in any validation error message is determined in the following ways:
- Using the value of any corresponding label tag. To do this you set the id of the label so that it has the same name as the element you are validating once you remove the prefix which should be lbl (lbl=label). Eg for a control with an id="lstAge" the label should be id="lblAge"
- If no label is found with a corresponding id a function is called that takes the id of the control you are validating and tries to convert it to a nice description by calling a function that parses camel case text to convert to nice string. It does this by stripping any prefix (str,txt,lbl,num,dt) and then placing spaces before any capital letters eg dtDateOfBirth becomes Date Of Birth.
The script also trims extra white space and does some basic XSS hack checking.
An example of the script in action is below.