Link to home
Start Free TrialLog in
Avatar of maqskywalker
maqskywalker

asked on

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.

User generated image
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/

User generated image
If I choose Federal Tax ID it applies a mask like this 12-456789 to the textbox.

User generated image
If I choose Social Security it applies a mask like this 123-45-6789 to the textbox.

User generated image

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.

User generated image

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
Avatar of hielo
hielo
Flag of Wallis and Futuna image

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>
Avatar of maqskywalker
maqskywalker

ASKER

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');
                });
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial