applying conditional logic to jQuery Validation Plugin rules

Hi experts,

I have a html page where I'm using the  jQuery Validation plugin http://jqueryvalidation.org

I have this working fiddle created:

http://jsfiddle.net/kd81p53k/2/


When you run the fiddle you see this. A Drop Down list, a textbox and a button. The button is disabled on page load.

on run of my fiddle
The dropdownlist has these 2 possible selections. Depending on which of these 2 formats you select it applies a specific format mask using the jQuery Masked Input plugin http://digitalbush.com/projects/masked-input-plugin/

the choices from the dropdown
If I choose Federal Tax ID it applies a mask like this 12-456789 to the textbox.

federal tax id mask applied to textbox
If I choose Social Security it applies a mask like this 123-45-6789 to the textbox.

social security masking applied to textbox

The masking on my example works just fine.

My question is on the validation I'm applying to my textbox.

if you look at the JavaScript of my fiddle these are the key parts.

Depending on the selected item from the dropdownlist I'm applying the mask to the textbox like this.
// *********** Mask ***********
if ($('#DropDownList1 option:selected').val() == '1') {
// 1 - FEIN - Federal Tax Id Number
// clear value in textbox
$('.TextBox1').val(""); // clear out the textbox value
$('.TextBox1').unmask("")
$('.TextBox1').mask("99-9999999"); // set textbox mask
} else {
// 2 - SSN - Social Security Number
// clear value in textbox
$('.TextBox1').val("");
$('.TextBox1').unmask("")
$('.TextBox1').mask("999-99-9999");
}
// *********** Mask ***********

Open in new window


If you look look lower down in the javascript section in the validation section i have this snippet:
These are the custom rule methods I created for the two formats I am using.
I have two method for social format and two for federal tax id format.
These methods work just fine because I have tested them individually.

// ***** Custom Methods *****

// custom validation method - check SSN for nine digits
jQuery.validator.addMethod("SSNCheck1", function (value, element) {
return this.optional(element) || /^\d{3}-\d{2}-\d{4}$/.test(value);
}, "Please enter a 9-digit Social Security Number.");

// custom validation method - check SSN for all zeros
jQuery.validator.addMethod("SSNCheck2", function (value, element) {
return this.optional(element) || value != "000-00-0000";
}, "All zeros are not allowed.");

// custom validation method - check FEIN for nine digits
jQuery.validator.addMethod("FEINCheck1", function (value, element) {
return this.optional(element) || /^\d{2}-\d{7}$/.test(value);
}, "Please enter a 9-digit Federal Tax Id Number.");

// custom validation method - check FEIN for all zeros
jQuery.validator.addMethod("FEINCheck2", function (value, element) {
return this.optional(element) || value != "00-0000000";
}, "All zeros are not allowed.");

// ***** Custom Methods *****

Open in new window


If you notice in my fiddle, in the rules section currently i'm applying the rules like this.
Right now only the validation rules work when I select social security.

// apply the following rules to the textbox called TextBox1
TextBox1: {

    // calls the validator method called SSNCheck1 which checks for nine digits
    SSNCheck1: true,
    // calls the validator method called SSNCheck2 which checks for all zeros
    SSNCheck2: true,

}


Here is a video showing my fiddle:  VIDEO DEMO

When I select social and type in 9 digits the validation passes and the button becomes enabled.

my validation rules working on social security format

Is there a way to either with an if statement or with some jquery validation property do revise my fiddle to do the following:

Is there a way to replace this:

// apply the following rules to the textbox called TextBox1
TextBox1: {

    // calls the validator method called SSNCheck1 which checks for nine digits
    SSNCheck1: true,
    // calls the validator method called SSNCheck2 which checks for all zeros
    SSNCheck2: true,

}

Open in new window


with something like this:

// apply the following rules to the textbox called TextBox1
TextBox1: {

if ($('#DropDownList1 option:selected').val() == '1') {
    // if  Federal Tax ID Number is chosen from the dropdown list apply these rules to textbox
    // calls the validator method called FEINCheck1 which checks for nine digits
    FEINCheck1: true,
    // calls the validator method called FEINCheck2 which checks for all zeros
    FEINCheck2: true,
} else {
    // if Social Security Number is chosen from the dropdown list apply these rules to textbox
    // calls the validator method called SSNCheck1 which checks for nine digits
    SSNCheck1: true,
    // calls the validator method called SSNCheck2 which checks for all zeros
    SSNCheck2
}

Open in new window



Anyone know the syntax to do something like that?

Essentially, in plain english...

if  Federal Tax ID Number is chosen from the dropdown list apply these rules to Textbox1
    FEINCheck1: true,
    FEINCheck2: true
otherwise if Social Security Number is chosen from the dropdown list apply these rules to Textbox1
    SSNCheck1: true,
    SSNCheck2: true
LVL 1
maqskywalkerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
You need to use the rules method:
http://jqueryvalidation.org/rules

On <select> change, you need to remove() the existing rules bound to the <input>.  Then immediately add the new effective rules.

For instance, let's say you have <input id="Textbox1"/>, then
// this removes all the rules that were previously "bound" to Textbox1.
$('#Textbox1').rules('remove');

// by contrast, if you wanted to remove only a specific rule, then the syntax would be:
$('#Textbox1').rules('remove', 'SSNCheck1');

// to add a rule:
$('#Textbox1').rules('add', {'SSNCheck1':true, 'SSNCheck2':true});

See below:
        $(document).ready(function () {
            //-------------------------

            // ****** On Page Load event ******
            // on page load disable the button
            $("#Button1").attr({ disabled: "true" });
            // ****** On Page Load event ******

            // ****** textbox on keyup event ******
            $("#TextBox1").on("keyup", function () {

                if ($("#TestForm1").valid()) {
                    $('#Button1').prop('disabled', false);
                } else {
                    $('#Button1').prop('disabled', true);
                }

            });
            // ****** textbox on keyup event ******

            // ****** dropdownlist change event function ******
            $('#DropDownList1').change(function () {

                // textbox is hidden by default
                // show textbox on change of dddl
                $('#TextBox1').show();
                
                // *********** Mask ***********

                if ($('#DropDownList1 option:selected').val() == '1') {
                    // 1 - FEIN - Federal Tax Id Number
                    // clear value in textbox
                    $('.TextBox1').val(""); // clear out the textbox value
                    $('.TextBox1').unmask("")              
                    $('.TextBox1').mask("99-9999999"); // set textbox mask
                    $('.TextBox1').rules('remove');
                    $('.TextBox1').rules('add',{'FEINCheck1':true, 'FEINCheck2':true});
                } else {
                    // 2 - SSN - Social Security Number
                    // clear value in textbox
                    $('.TextBox1').val("");
                    $('.TextBox1').unmask("")                  
                    $('.TextBox1').mask("999-99-9999");
                    $('.TextBox1').rules('remove');
                    $('.TextBox1').rules('add',{'SSNCheck1':true, 'SSNCheck2':true});
                }

                // *********** Mask ***********
            });
            // ****** dropdownlist change event function ******


                // *********** Validation ***********

                // ***** Custom Methods *****

                // custom validation method - check SSN for nine digits
                jQuery.validator.addMethod("SSNCheck1", function (value, element) {
                    return this.optional(element) || /^\d{3}-\d{2}-\d{4}$/.test(value);
                }, "Please enter a 9-digit Social Security Number.");

                // custom validation method - check SSN for all zeros
                jQuery.validator.addMethod("SSNCheck2", function (value, element) {
                    return this.optional(element) || value != "000-00-0000";
                }, "All zeros are not allowed.");

                // custom validation method - check FEIN for nine digits
                jQuery.validator.addMethod("FEINCheck1", function (value, element) {
                    return this.optional(element) || /^\d{2}-\d{7}$/.test(value);
                }, "Please enter a 9-digit Federal Tax Id Number.");

                // custom validation method - check FEIN for all zeros
                jQuery.validator.addMethod("FEINCheck2", function (value, element) {
                    return this.optional(element) || value != "00-0000000";
                }, "All zeros are not allowed.");

                // ***** Custom Methods *****

                // if the validation passes then use label.valid css class
                jQuery.validator.setDefaults({
                    debug: true,
                    success: "valid"
                });

                    $("#TestForm1").validate({
                          rules: {

                            // apply the following rules to the textbox called TextBox1
                            TextBox1: {
                                // calls the validator method called SSNCheck1 which checks for nine digits
                                SSNCheck1: true,
                                // calls the validator method called SSNCheck2 which checks for all zeros
                                SSNCheck2: true,
                            }

                        },
                        submitHandler: function (form) {
                            alert("submitted.");
                        }
                    });

                // *********** Validation ***********
            
            //-------------------------
            // end of document ready function
        });

Open in new window


Also, since you are providing initial rules to make SSN the default check, having a "blank" <option> doesn't make sense.  I suggest you get rid of it and change SSN to <option selected="selected" value="2">SSN</option>
0
maqskywalkerAuthor Commented:
Once i revise  the mask section like this which is how you mentiond

                // *********** Mask ***********

                if ($('#DropDownList1 option:selected').val() == '1') {
                    // 1 - FEIN - Federal Tax Id Number
                    // clear value in textbox
                    $('.TextBox1').val(""); // clear out the textbox value
                    $('.TextBox1').unmask("")
                    $('.TextBox1').mask("99-9999999"); // set textbox mask
                    $('.TextBox1').rules('remove');
                    $('.TextBox1').rules('add', { 'FEINCheck1': true, 'FEINCheck2': true });
                } else {
                    // 2 - SSN - Social Security Number
                    // clear value in textbox
                    $('.TextBox1').val("");
                    $('.TextBox1').unmask("")
                    $('.TextBox1').mask("999-99-9999");
                    $('.TextBox1').rules('remove');
                    $('.TextBox1').rules('add', { 'SSNCheck1': true, 'SSNCheck2': true });
                }

Open in new window


What do I need to but in here in the TextBox1 rules part shown below?
Right now I have this but that's not correct?

                $.fn.ready(function () {
                    $("#TestForm1").validate({
                        rules: {

                            // apply the following rules to the textbox called TextBox1
                            TextBox1: {

                                SSNCheck1: true,
                                SSNCheck2: true
                            }

                        },
                        submitHandler: function (form) {
                            alert("submitted.");
                        }
                    });

                    //alert('foo');
                });
0
hieloCommented:
You don't need to wrap the call to validate() in $.fn.ready(function () {})  (as a matter I fixed that on my post).

You can leave the rules as you have them, which makes SSN the default validation rule:
$("#TestForm1").validate({
                        rules: {

                            // apply the following rules to the textbox called TextBox1
                            TextBox1: {

                                SSNCheck1: true,
                                SSNCheck2: true
                            }

                        },
                        submitHandler: function (form) {
                            alert("submitted.");
                        }
                    });

Open in new window

But also make the <select> list default to SSN:
<select id="DropDownList1" name="DropDownList1" class="DropDownList1">
                                <option value="1">Federal Tax Id Number</option>
                                <option selected="selected"  value="2">Social Security Number</option>                                                           
                            </select>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.