Javascript - Good Form Validation
<input type="text" class="required email"/>

The above convention indicates that the field is required and it must be an email address. Our JavaScript code will loop through all the form fields, pull the attributes out of the class, and act on them from there. The class attribute serves a dual purpose here, because it can also be used with CSS to style the field.

The JavaScript reads the metadata (the information that describe the data) from the class attribute and acts on the data based on those rules, but at this point, the data and metadata are still tightly intertwined with the structure and semantics of the markup. Additionally, this method is limited. It is hard to have conditional logic embedded within the HTML. For instance, it is hard to say that a field is required based on the value of another field. Well, we can, but it is a bit awkward:

<input type="checkbox" name="other" id="other"/>
<textarea type="text" class="dependsOn-other" id="tx"></textarea>

The dependsOn prefix indicates that the textarea depends on the value of another field (and in this case, on other). To avoid this awkward situation, let's look at defining this business logic in JavaScript:

var fields = {
    'other': {
        required: true
    'tx': {
        validation: function() { .. }

ExtJS has vtype, and it allows us to define our own custom vtype and the corresponding validation function. Similarly, we can define class="vtype-vTypeName" and have our JavaScript code determine the name of the vtype from this metadata and invoke the appropriate validation function associated with this vtype.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License