Chapter 3. Validation
Validating the data that users provide in web forms is an important step in exchanging information with them. Web applications should not hit the network with blank form information or fields that contain nonnumeric characters where numbers (such as a credit card number or ZIP Code) are required. To prevent this, JavaScript provides an option to implement client-side validation: a form can self-check before the code connects with the server and submits the data. The client represents the first layer of validation an application can implement. A second layer of validation on the server is critically important, for example, when the data involves financial or other private information, or if JavaScript is disabled in the user’s browser. Server-side validation is required to ensure that the application handles valid data. The following hacks demonstrate validation techniques for blank text controls, email addresses, credit card numbers, and U.S. ZIP Codes.
Validate a Text Field or textarea for Blank Fields
Spare the network an unnecessary hit if the user leaves any required form fields blank.
No web developers want their Ajax applications to hit the
network with requests if the users leave necessary text fields blank.
Thus, checking that input
elements of type text
and the large boxes called textarea
s in HTML
contain values is one of the most common forms of validation.
This hack shows the code for checking if a text control is blank. The inline
Get Ajax Hacks now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.