Douglas Crockford
has dubbed Javascript “the world's most misunderstood programming
language.” If he is correct, and I believe he is, then it should be no
surprise that a good deal of Javascript development is tainted by
“AntiPatterns”.
An AntiPattern quite simply is what does not work. Let's consider what this means on a couple of different levels, within the context of validating form data with Javascript.
First
lets consider specific code that “does not work”. Recent books have
gotten better at avoiding the following sort of thing, but it remains
widespread to this day (to keep this example as brief as possible I'm
not including any code that would provide feedback to the user, such as
a Javascript alert).
|
<form onsubmit= 'return this.fname.value != "" && this.lname.value !=""'> First Name: <input type="text" name="fname"> <br> Last Name: <input type="password" name="lname"> <br> <input type="submit" value="Log In"> </form> |
If the user enters absolutely nothing into either fname or lname, the
form's onsubmit handler will return false and the form will not be
submitted. The code successfully prevents submitting completely empty
fields.
It
does not however prevent the user from entering spaces into those
fields. It is therefore not enough to test against the empty string “”.
The
solution is to test against a “regular expression” object. For the
uninitiated, “regex”'s, as they are also sometimes called, represent a
pattern of characters. For the task at hand, we are going to use a very
simple pattern: /\S/
The
first thing to notice are the beginning and ending slashes. These
simply signify that what's between them is the expression, not unlike
quotation marks signifying that they contain text.
Within the slashes, the pattern \S stands for any non-whitespace character. Regular expressions in Javascript have some useful built in methods, including test() , which returns true or false depending on whether a string passed as an argument matches the pattern.
So
in the above example we can just switch the onsubmit event handler to
the following, and it will not only reject completely empty fields, but
also fields containing only whitespace, such as spaces:
| onsubmit='return /\S/.test(this.fname.value) && /\S/.test(this.lname.value)' |
Substituting the above, now both name fields must contain some non-whitespace characters in order for the form to get submitted.