Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQueryValidate - Required field - depends doesn't work

With jQueryValidate, I'm trying to make a field required only if another specific field is empty. So, after searching on the Internet, I did this :

rules: {
     marque: {
          required: {
               depends: function() {
                    if (($('#add_marque').val() == "Ajouter une marque" && $('#marque').val() == -1) || ($('#add_marque').val() == "" && $('#marque').val() == -1)) {
                         return true;
                     }
                     else {
                         return false;
                     }
               }
          }
     }
}

Unfortunately, it doesn't work. But, if I do this :

depends: function() {
     if (($('#add_marque').val() == "Ajouter une marque" && $('#marque').val() == -1) || ($('#add_marque').val() == "" && $('#marque').val() == -1)) {
          alert("Here!");
          return true;
      }
      else {
           return false;
      }
}

The alert box appears. So, my test seems to work. Can anyone tell me what I did wrong? I'm using jQuery 1.8.3 and qTip2 with jQueryValidate. Thank you very much!

like image 491
Lancelot Avatar asked Jun 15 '13 20:06

Lancelot


2 Answers

Your syntax and use of the plugin is correct from what you have given. You need to troubleshoot, so first try this

marque: {
    required: true;
}

simple. Does the error message appear? If yes then try this

marque: {
    required: {
        depends: function () { return true; /* or false */ }
    }
}
like image 174
Dr Blowhard Avatar answered Oct 27 '22 19:10

Dr Blowhard


You really should be able to do this without the depends option, just make the function work directly on the required object:

rules: {
     marque: {
          required:  function() {
                 if (($('#add_marque').val() == "Ajouter une marque" && (('#marque').val() == -1) || ($('#add_marque').val() == "" && $('#marque').val() == -1)) {
                     return true;
                 }
                 else {
                     return false;
                 }
          }
     }
}

See a working, simpler example here: http://jsfiddle.net/ryleyb/3hqH6/1/

like image 32
Ryley Avatar answered Oct 27 '22 19:10

Ryley