Client-side validation is optional but has benefits, including faster response to the user than server-side validation, a reduction in web-server load, and a reduction in network traffic. Moreover, client-side validation can be implemented as interactive validation, not only as post-validation, as on the server side. However, validation in the client tier is unreliable: the user can bypass the validation through design, error, or configuration. For that reason, client-side validation is a tool that should be used only to improve speed, reduce load, and add features, and never to replace server-side validation.
This example is designed to check if a
userName field contains whitespace and, if so, to show a dialog box containing an error message to the user. The dialog box is shown in Figure 7-1.
Figure 7-1. The dialog box produced when whitespace is entered in the userName field
containsblanks( ), is executed when the user submits the
The function call is part of the
<form onSubmit="return(containsblanks(this.userName));" method="post" action="test.php">
When the submission event occurs-the user presses the Submit button-the
onSubmit action handler is triggered. In this case, the function
containsblanks( ) is called with one parameter,
this.userName. The object
this refers to the
<form> itself and the expression
this.userName refers to the input widget within the
<form>. The function call itself is wrapped in a
return( ) expression. The overall result of executing
containsblanks( ) is that if the function returns
<form> isn't submitted to the server; if the function returns
true, the HTTP request proceeds as usual.
containsblanks( ) works as follows:
forloop repeatedly performs actions on the characters entered by the user. The expression
s.value.lengthrefers to the length of the string value entered by the user into the
lengthproperty is one of the predefined properties of the
valueattribute of the
Each character in the string entered by the user is stored in a character variable
s.value.charAt(i)is again an expression related to the value entered by the user in the
valueattribute of the widget has an associated function (or, more correctly, a method) called
charAt( )that returns the value of the character at the position passed as a parameter. For example, if the user enters
testin the widget,
ifstatement checks whether the current character is a space, a tab character, or a carriage return. If so, the
alert( )function is called with an error string as a parameter. The
alert( )function presents a dialog box in the browser that shows the error message and has an OK button, as shown in Figure 7-1. When the user clicks OK, the function returns
false, and the submission process stops.
If the string doesn't contain any whitespace, the function
true, and the
<form>submits as usual.
Note that the HTML comment tags are included inside the
onSubmit event handler in the