Wednesday, October 14, 2009

JQuery dependent form field validation

At work I use a lot of JQuery. It is amazing, I can't even remember
the days when I'd write my own form validation or other such heavy JS
code. 99% of the time JQuery is amazing, but that last 1% is when you
have pushed too hard and are in a corner with a deadline approaching..

Such is the case with a recent project. I had a form which had
several fields on it. To help "Joe User" (when "User" means "Pothead"
or other such lower form of life), we changed the page from two forms
which beautifully inserted data into separate tables to one monster
form that submitted data to a controller which decided which data went
into which table.

There was the equivalent of shipping address information on the top
and items to be shipped on the bottom. The address information might
be updated separate from the shipping data on the bottom. The problem
is that the bottom part of the form would be blank, which the
controller can handle (if blank, don't insert it -duh). The problem
is that in validation, a shipping item might need to have a item
number and price but making them required would trigger a validation
problem when just hitting submit after changing the address.

So I needed the required shipping item information to be required when
filled in, but ignored otherwise. The trick is to use the "rules"
block inside the form.validate() statement, and add a function that
returns true or false to set or unset the fields to be required. I
finally found the answer in the JQuery Docs (
). I did the copy-paste-alter thing and violah! It didn't work...

WHY! Hours had turned to days on this one issue.. and it still would not work!

Ok, I calmed down and found out the following is IMPORTANT:

- Name and ID synchronization: Do yourself a favor and keep the form
inputs' names and IDs the same. The $("#name") is obviously the ID
but less obvious, the rules block in the Validate method point to the
input's NAME. Keep them the same and life is good.

- JavaScript form submission: It is what the cool kids are doing, but
it can interfere with the form validation. When the regular submit
button was pressed the form validated and would error properly. When
the JavaScript based link was used the form would error but submit
anyhow. Not great because that allowed bad data to be inserted into
the database.

So, I wish you all good luck and hopefully you will read this and say
"pft, I am no idiot, I knew that" but you have that luxury at this
point, I would have said the same thing (as I took note of this

No comments:

Popular Posts