tags:

views:

331

answers:

1

Gentlepeeps,

I'm new with Jquery. Apologies in advance for the basic question.

I'm trying to bring in Jquery to our struts/jsp environment. Existing code is riddled with pure javascript.

I'm writing a validation rule using JQuery's validation plugin like so:

$("#advanceValidateform").validate({ 
 rules: { 
  advanceAmt1: { min: 0, max: 23 },
  advanceAmt2: { min: 0, max: 24 },
  advanceAmt3: { min: 0, max: 26 }
  }

});

The problem is:

  1. The values for max, min cannot be hard-coded but has to come from my action class (probably from the request). I usually do this by calling parameters in my jscript function (scriplet code passing the exact values).
  2. advanceAmt1, 2 and 3 come from a loop

A solution would be to parameterize the whole thing, have a validation rule for advanceAmt with parameters min, max and call that for each input element containing the "class" .advanceAmt .

essentially I require the jquery validation to :

  1. run on all elements with a "class" say .advanceAmt
  2. and pick up the parameters min, max from the input tag itself,(from scriplet i can generate a min=<%=x%> and max=<%=y%> )

But i'm a little lost how to do the same with jquery. Is this possible? If not any suggestions or better alternatives?

Thanks in advance. K

+2  A: 

On your JSP page you can use a JSTL iterator to go through the collection of validation rules and generate each one. This does not affect the javascript code because the JSTL evaluates on the server and the resulting JavaScript evaluates on the client.

For example, suppose you have a collection of validation rules called validations that was created by your action.

  $("#advanceValidateform").validate({ 
    rules: { 
      <c:forEach var="v" items="${validations}" varStatus="loop">
         advanceAmt${v.id}: { min: ${v.min}, max: ${v.max} }${!loop.last ? ',' : ''}
      </c:forEach>  
    }
  });

Some assumptions - Your collection of validation rules contain three properties id, min and max. The if statement was necessary to add a comma between the rules but not after the last one.

Hope this helps a bit.

Vincent Ramdhanie
I've optimized your `c:forEach` example to take advantage of `varStatus` ;)
BalusC
@BalusC Thanks, that is actually a very good use of varStatus...I never considered it before...only used it to color different rows etc.
Vincent Ramdhanie
For other (useful) methods, check http://java.sun.com/javaee/5/docs/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html
BalusC
Vincent+BalusC you chaps rock!
Kaushik Gopal