views:

279

answers:

1

I am trying to clean up some of the JavaScript throughout my views and one of the things I would like to do is move my jQuery Validation code to an external script function and pass in references to the fields I need to process/validate. The issue I am facing is pertaining to how the signature of jQuery Validate's rules field is formatted:

$("#form").validate({
 rules: {
  txtNoSpam: {
   remote: WebSettings.SpamFilterValidationUrl
  }
 },
 messages: {
  txtNoSpam: {
   remote: "Answer is incorrect."
  }
 },
});

In the above code 'txtNoSpam' maps directly to an element on my page called txtNoSpam, but I would much rather pass txtNoSpam into my initialization function as an object and then map the validation to the correct field using the supplied object's element name as the parameter name:

function Init(form, field1)
 form.validate({
  rules: {
   field1.attr('name'): {
    remote: WebSettings.SpamFilterValidationUrl
   }
  },
  messages: {
   field1.attr('name'): {
    remote: "Answer is incorrect."
   }
  },
 });
}

Is there any way I can achieve this?

+1  A: 

try construct validation options in steps so you can use []. See example below:

function my_validate(field_name) {
   var opts = {rules:{},messages:{}};
   opts.rules[field_name] = {remote: WebSettings.SpamFilterValidationUrl};
   opts.messages[field_name] = {remote: "Answer is incorrect."};
   form.validate(opts);
}

UPDATE: Considering your updated question, here is the Init:

function Init(form, field1)
   var opts = {rules:{},messages:{}};
   opts.rules[field1.attr('name')] = {remote: WebSettings.SpamFilterValidationUrl};
   opts.messages[field1.attr('name')] = {remote: "Answer is incorrect."};
   form.validate(opts);
}
Piotr Czapla
How do you mean ?
Piotr Czapla
Nevermind actually. I get it now. :)
Nathan Taylor