views:

31

answers:

1

I am using jquery validation plugin to validate my form on client side. I am adding a new method using addMethod function for every HTML control which have regex (custom) attribute. My HTML control would look like.

<input type="text" id="txtInf" name="txtInf" regex="some regular exp" error="check your inf"></input>


$("*[regex]").each(function () {

                  var controlId = $(this).attr('name');    
                  var regex = new RegExp((this).attr('regex'));    
                  var error = $(this).attr('error');    

            $.validator.addMethod(controlId, function (value, element) {

                return this.optional(element) || false;

            }, error);



            $(this).rules("add", { '" + controlId + "': "^[a-zA-Z'.\s]{1,40}$" }); 

            $(this).validate();



        });

Here I am giving method name as controlId which is txtInf. In below line, I need to give txtInf, but I want to use controlId variable instead, as I want to make this funtion a generic one. But if I write controlId directly, it searches for the method with the same. But added method is txtInf actually. So I need some way to generalise this line by using controlId variable.

$(this).rules("add", {txtInf: "^[a-zA-Z'.\s]{1,40}$" }); 
A: 

The problem is that you can't use a variable name for referencing in an object literal. What I've done in the past when I need to do something like this is to manually create the JSON string and pass it through parseJSON. this would look something like:

$(this).rules("add", $.parseJSON('{"' + controlId + '":"^[a-zA-Z\'.\s]{1,40}$" }'); 
PriorityMark