1

I have to validate a form like this:

$('#formfile').validate({
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    ignore: '',
    //focusInvalid: true,
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
        element.focus();
    },
    rules: {
        if(country == "INDONESIA") {
            tax: {
                required: true              
            }
        }
    },
    messages: {
        if(country == "INDONESIA") {
            tax: "Please insert file Tax"
        }
    }
});

Can I do that? I want to check if Country is Indonesia or not, and if Country is Indonesia that field must be mandatory. Otherwise, if Country is not Indonesia, that field can be ignored. Any suggestion?

Edit: I forgot I used variable to get Country - var Country = $('#country').val();

MAXE
  • 4,978
  • 2
  • 45
  • 61
Wolfzmus
  • 463
  • 1
  • 10
  • 23

2 Answers2

0

Try this ;)

You could use depends:

...
    rules: {
        tax: {
            required: {
                depends: function(element) {
                    return ($('#country').val() == 'INDONESIA');
                }
            }
        }
    }
...

Jquery validate depend field

Community
  • 1
  • 1
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
0

You could use the inline conditional operator to do it:

        rules: {
            country=="INDONESIA" ? 
              {
                  tax: {
                      required: true              
                  }
              } 
              : { }
Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30