Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use field name variable in JQuery validation rules

I am a jquery newbie. I could get the validation rules working in my form. I am using a Java framework and for some reason, when it converts from .xhtml to .html, all the ui component's id/name were prefixed with the form that containing it. I would like to reuse these validation rules for two other forms but because of the prefix issue, I would need to use js variable and pass the formId to the function. For some reason, this gives me a problem:


NOT WORKING

var positionTitle = "#myForm:positionTitle";

$("#" + formId).validate({

  rules:{
        positionTitle : {required:true, maxlength:50},
            ...

WORKING

$("#" + formId).validate({

  rules:{
         "#myForm:positionTitle" : {required:true, maxlength:50},
              ...
like image 866
blu3_ros3 Avatar asked Mar 02 '26 16:03

blu3_ros3


1 Answers

After you call .validate() on the form, you an do this:

$("[name='" + positionTitle + "']").rules("add", {required:true, maxlength:50});

...but you can't use the variable as a name in an object literal like that.

The other option is constructing the rules object before it gets passed into validate(), but that gets a bit messy as well, I can't say which is better based on the question, but if you have many of these, you may want to go the rules building route.

like image 176
Nick Craver Avatar answered Mar 05 '26 04:03

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!