Thursday, December 12, 2024

A Case for A Case


Simplify that Mountain of
JavaScript Validation Code.

So there you are with your nice
new form, neatly coded into your HTML page, proudly showing it off to your boss,
when she says “So when they fill out the form you check to see that they put
numbers in the number fields and that if they ask for a top they also ask for a
base and all that sort of thing, right?”  “Ummmm, sure. That’s exactly what it’s
going to do.  Right after I put in the next piece of code that I was about to
write.”  Off you go to your corner and kick yourself for not getting written
requirements specifications!  Then you think about what to write for validation
code and of course, JavaScript pops right into your mind.  JavaScript is an
excellent tool for validating forms.

When you write your JavaScript code, however, it can
quickly start to get complex or lengthy.  In the simple scenario above when have
an example of dependency.  “If they ask for a top, they must also ask for a
base.”  This means if “Top” is selected and “Base” is not selected, there is an
error.  The values expected for “Base” depends on the value provided for “Top”.

Let’s code it.  To explain the logic, I’m going to use
something called “pseudocode”.  Pseudocode is English-like, but laid out like a
programming language.  It allows us to look at the logic we’ll use in a piece of
code without worrying about the exact niceties of the programming language’s
syntax. Try this:

if top-selected is yes,
   if base-selected is not yes
            display error “Base is needed for Top”
            return to form
  end-if
end-if

See how that works?  We’ll look at the logic in this way
until we see the full concept and then we’ll translate it into some actual code.

Let’s see what happens when the problem gets a bit more
complex.  Suppose we have two sets of options on our form whose values depend on
each other.  Let’s also suppose that there’s plenty of text on our form to
explain all these requirements to our users!  In our example, assume that if Top
type 1 or 2 is selected, Base can be type 1, 2, 5 or 6.  If Top type 3 is
selected, however, the base must be type 2, 3, 4, 6 or 7.  Assume that we have
used a pair of drop down lists (aka Select boxes, aka Pop-up boxes) and that the
first choice is “None Chosen”. The “selectedIndex” property of a dropdown box
tells us which choice was made, so let’s look at some pseudocode.

We can first check whether a top was chosen at all, and if
not we make sure no base was chosen.

 if top.selectedIndex is zero,
   if base.selectedIndex is greater than zero
            display error “Sorry, no Top means no Base either”
            return to form
  end-if
end-if

That’s just about the reverse of our earlier example, but
it gets that error out of the way before we get too complicated.

Next, we start the validation of the options.

if top.selectedIndex is 1
   if base.selectedIndex is zero
            display error “Base is needed for Top”
            return to form
  end-if
end-if

if top.selectedIndex is 1
   if base.selectedIndex is 3
            display error “Sorry, wrong base for top type 1”
            return to form
  end-if
end-if

if top.selectedIndex is 1
   if base.selectedIndex is 4
            display error “Sorry, wrong base for top type 1”
            return to form
  end-if
end-if

Wait a minute!  We’ve only done a couple of the errors for
the first of three possible choices for Top type.  Before we’re done we’ll have
a mountain of code here!  There must be a better way.  And, there is!

Suppose we said “in the case where the Top choice is one,
Base choices cases 1. 2. 5. 6 are ok and anything else is an error.”  That looks
more compact.  We’re now looking at cases.  Programatically, we’ll say what
the item is we need to inspect, and then say what to do in each case.  Something
like:

select Top
    case 1
            select Base
               case 1
                        Continue, we’re ok
               case 2
                        Continue, we’re ok
               case 5
                        Continue, we’re ok
               case 6
                        Continue, we’re ok
               default
                        display error “Sorry, wrong top and base combination”
                        return to form
               end-select
    case 2
            select Base
               case 1
                        Continue, we’re ok 

and so on.  In this way, we have not only dramatically
reduced the overall amount of code we need, but we have greatly clarified it. 
This will make for much easier changes later on.

This type of structure is commonly known as a “Select-Case”
structure or simply a Case structure.  Just to make life complicated
(actually, to avoid confusion with other select items) JavaScript calls it
switch instead of Select.  Using this structure can save a lot of heartache!

Here’s what our example looks like in JavaScript code
(assume we’re in a validation function):


switch(theForm.top.selectedIndex)
 { case 1:
      switch(theForm.base.selectedIndex)
       {    case 1:  break;
            case 3:  break;
            case 4:  break;
            case 6:  break;
            default:
             { alert("Sorry, wrong top and base combination.");
               theForm.top.focus();
               return (false);
             }
       }
  case 2:
      switch(theForm.base.selectedIndex)
       {    case 1:  break;
            case 3:  break;
            case 4:  break;
            case 6:  break;                 
            default:
             { alert("Sorry, wrong top and base combination.");
               theForm.top.focus();
               return (false);
             }
       }
  case 3:
      switch(theForm.base.selectedIndex)
       {    case 2:  break;
            case 3:  break;
            case 4:  break;
            case 6:  break;                              case 7:  break;
            default:
             { alert("Sorry, wrong top and base combination.");
               theForm.top.focus();
               return (false);
             }
       }
 }

That’s the entire validation!

There are a lot of  JavaScript particulars used in this
example.  It was not my intention in this short piece to explain all those
details, but rather to familiarize you with the structure.  This structure
exists in most modern languages, so if you know it’s there and you know how the
logic works, you’ve only got to deal with the particular syntax of the language
you choose in order to use it.  If you need to familiarize yourself with forms,
check this out:

Goodies Forms Tutorials
  For JavaScript basics, try this:
Coding can be a lot of fun when you know how to cut down on
the tedious parts, but can still produce some sophisticated stuff!

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured