views:

50

answers:

1

On my client registration form I have the following rules

// Define the div containing validation messages
var container = $('#clientErrorWrapper');
// Start validation routine 
// validate the form when it is submitted
var validator = $("#frmEdit").submit(function() {
    // update underlying textarea before submit validation
    tinyMCE.triggerSave();
    }).validate({
    errorContainer: container,
    errorLabelContainer: $("ul", container),
    wrapper: 'li',
    // start rules (add new rules as necessary)
        rules: {
            firstname: {
                required: true
            },
            lastname: {
                required: true
            },
            email: {
                required: true
            },
            address1: {
                required: true
            },
            city: {
                required: true
            },
            state_province: {
                required: function(element) {
                    return $("#country").val() == 'US';
                  }
            },
            postcode: {
                required: true
            },
            country: {
                required: true
            }
    // finish rules
    }

I would like to extend the state_province rules so that this field is required if country equals CA or AU as well, how can I achieve this please.

+3  A: 

You can do:

        state_province: {
            required: function(element) {
                var c = $("#country").val();
                return c=='US' || c=='CA' || c=='AU';
              }
        }

No need to get more complicated than that unless your list gets a bit longer.

If however the list grows, you can use jQuery's .inArray():

        state_province: {
            required: function(element) {
                return $.inArray($("#country").val(), ['US','CA','AU']) > -1;
              }
        }
Nick Craver
Nick,thanks your 1st solution works perfectly but the 2nd shows the following error in firebug invalid object initializer
I-CRE8
@I-CRE8 - Woops, use `[]` instead of `{}` for Arrays, answer updated.
Nick Craver
Fabulous thanks Nick.
I-CRE8