Categories:

Flag Variables, Validation, and Function Control

Credits: This tutorial is written and contributed by Alex Vincent. Edited by JavaScript Kit. Alex is a long time visitor of JavaScript Kit, and participant of CodingForums.

Have you ever had to validate a form in JavaScript?  If you've built forms in HTML, you probably know by now you can never be certain what your clients will put in those forms.  Sure, you can tell them what they are supposed to put in a form, but if your directions are not followed, you may receive bad results from the form.  Validation of a form is one of the most common uses of JavaScript there is out there (although most coders would prefer to validate a form on the server side, in an environment they can control).

What about validating a function's arguments?  Most people have never considered this.  In 99% of all cases, it's not necessary -- your JavaScript functions receive calls only from HTML or JavaScript you write.  I, however, like to develop code and tutorials for other people to use.  So my functions must invariably assume they are receiving bad arguments.  I need to develop validation rules for the arguments in a function, or else my functions may fail.

This tutorial covers three main subjects:  the definition of a flag variable, validating a form's inputs or a function's arguments, and advanced techniques for function-internal error handling (including one I just discovered).  So get out those notebooks and fire up your text editor, because you'll need them.

What is a flag variable?