views:

343

answers:

5

Hi, I need help validating a form, preferably using JQuery:

this is my code:

<form action='index.php' method='post'> 
<table> 
<tr> 
  <td>1.</td> 
  <td><select name='from_1'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
  <td><select name='to_1'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
</tr> 
<tr> 
  <td>2.</td> 
  <td><select name='from_2'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
  <td><select name='to_2'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
</tr> 
<tr> 
  <td>3.</td> 
  <td><select name='from_3'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
  <td><select name='to_3'><option>HOME</option><option>A</option><option>B</option><option>C</option></select></td> 
</tr> 
</table> 
<input type='submit' value='submit' /> 
</form>

I want to add some javascript validation:
when someone clicks on the submit button, the form should be validated (see below).
When it is invalid, an error message should popup (alert or -even better- modal dialog), and the form should not be submitted.

The validation:
each row (in this example 3, but could be more) should contain one and only one time the 'HOME' selection. So either the 'from' or the 'to' option should be HOME.

Can someone help me with this? I know it is quite specific, but it will help me a lot...

+2  A: 

Have you looked at the jQuery validation plug-in, http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ? It's pretty easy to tweak and is based on adding classes to your elements (e.g. class="required" ).

Zachary
+1  A: 

Take a look to the jQuery Validation plugin, then you should be able to use the equalsTo method which accepts a css selector.

Boris Guéry
A: 

You give every select a class, ie 'validate':

<select name='from_2' class="validate">

Than you write a function to iterate through every such element which initially has some boolean variable set to false and when it finds 'HOME' within the values, it sets the variable to true. When it finds 'HOME' again it does what you want.

But, honestly, don't relly on client side validation.

shazarre
Hi, thanks already for this part... I will run some tests...I don't rely on client side validation, server side validation is already implemented...
Fortega
A: 

The jquery validation plugin was a big too much to handle right now :)

I solved it my own way... see the link

Fortega
+2  A: 

I have written a blog post titled "Metadata based validation with jQuery" which covers this topic. Additionally there is sample code showing how to use it in clear HTML (download is available at the bottom).

Marcin Obel