Validating Forms with CSS - J Query

Problem
You have a form that you would like to validate. To get started, you’ll want to set up some basic CSS. The only styles that are really important for this enhancement are the display:none declaration of the div.errorMessage selector and the display:block declaration of the div.showErrorMessage selector. The rest are just to make things look better:

The following HTML snippet is one example of how you might structure this form. The <div class="question>element is purely for layout and not important for the validation code. Each <label>element’s for attribute associates it with the form element with that identical id attribute. That is standard HTML, but I wanted to call it out because the JavaScript will also be using that (in reverse) to find the correct <label>for a given form element. Similarly, you’ll notice the error messages have an id attribute of error Message_ plus the name attribute of the associated form element. This structure may seem redundant, but radio buttons and checkboxes are grouped by the name attribute and you’d only want to have one error message per such group:

Solution

The first part of the solution is fairly straightforward. Find the <form>element, and hijack the submit event. When the form is submitted, iterate through the required form elements, and check to see whether the required elements are valid. If the form is error free, then (and only then) trigger the submit event:

The second part of this solution is where all the real validation happens. The isValid() method starts by storing frequently used data from the element we’re validating.
Then, in the switch() statement, the element is validated. Finally, class names are added to or removed from the <label>and div.errorMessage elements.

Discussion

The validation in this solution is quite simple. It checks the following:

  • <input type="text">, <input type="password">, and <textarea>elements have some data other than whitespace.

  • <select>elements have something other than the default option selected. Please note that there are two types of <select>element: “select-one” and “selectmultiple” (see the second code snippet in this section for HTML code and the previous code snippet for JavaScript validation). The first <option>element of the "select-one” <select>must have a value="" in order for validation to work. The “select-multiple” <select>is immune from this requirement because its <option>elements can be deselected.

  • <input type="radio">and <input type="checkbox">elements have at least one element checked in their respective name groups.

The switch(){} statement is used because it is more efficient than multiple if(){}else if(){} statements. It also allows for elements with shared validation to be groupedtogether, letting the break; statement separate these groups.
The validateElement object is in the global scope with the intention that it might be reused on other forms. It also keeps the global scope less cluttered by containing the validation methods—in the future, helper methods could be added to the
validateElement object without worrying about global naming collisions. For instance, a stripWhitespace() method could be implemented like this:

When we validate on submit, the dot notation is cleaner and more readable. However, let’s extend the bracket-notation solution to allow elements to revalidate (after an initial validation) using the change event. This would give the user immediate feedback that their new answers are in fact valid, without requiring them to click the submit button.
The following code does not work as expected (see the next paragraph for the real solution), but it illustrates where to .unbind() and .bind() the change event:

The problem with the previous code isn’t syntax but logic. You’ll note that the radio buttons in the HTML have the class="required" attribute. This means that when the entire form is validated, each radio button is validated, and (more importantly) each radio button’s <label>has a class added or removed to indicate the error. However, if we allow for a revalidation to occur using the element-specific change event, only that particular radio button’s <label>will be updated—the others would remain in an error state. To account for this, a single change event would have to look at all radio buttons and checkboxes in that name group to affect all the <label>classes simultaneously:

If the preceding code were to be rewritten using dot-notation syntax, it would have twice again as many lines. And on a separate note, with this new logic in place, only one radio button (or checkbox) in a name group would need to have the class="required" in order for all the other elements in that group to be adjusted correctly.
What will happen when JavaScript is disabled? The form will be submitted without client-side validation. Always be sure to validate code on the server. Don’t rely on JavaScript to provide clean data. If the server-side code returns the form with errors, it can use the same classes, on the same elements, in the same way. There is no need to use inline style tags or write custom code to handle the server-side errors differently.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics