0

would like to check if the driver license is exactly 6 numbers if the option field above is state DE jsfiddle code below

http://jsfiddle.net/THKez/1/

<form name="clientdetails_form" id="clientdetails_form" method="POST" action="xxxx.php">  

<p>
<label for="state">State</label>
<select type="text" name="state" >
<option value="NY">NY</option>
<option value="DE">DE</option></select>
</p>

<p>
<label for="LicenseN"><em>*</em>License #</label>
<input id="ClientLicensenNum"  name="ClientLicensenNum" type="text" value="" >
</p>    

    <input type="submit" value="submit"  >    

</form>

thanks

Nassim
  • 2,879
  • 2
  • 37
  • 39

2 Answers2

0

On change of the drop down, if the state is DE and the length is 6, do something. Fiddle

$(document).ready(function() {
    $('select').change(function() {
        var state = $(this).val();
        var license = $('#ClientLicensenNum').val();
        if (state == "DE" && license.length == 6) {
            console.log('Do something');
        }
    });
});​
pmandell
  • 4,288
  • 17
  • 21
0

Create a custom method to handle DE licenses with 6 characters:

jQuery.validator.addMethod("DELicense", function(value, element) {
    if (this.optional(element)) {
        return true;
    }

    if ($('select[name="state"] option:selected').val() == 'DE') {
        return $(element).val().match(/^\d{6}$/);
    } else {
        return true;
    }
}, "DE Licenses must be 6 numbers");

When you call validate, specify that this custom type must be used when your select is set to DE:

$("#clientdetails_form").validate({
    rules: {
        ClientLicensenNum: {
            DELicense: true,
            required: true
        }
    }
});​

See it in action here: http://jsfiddle.net/ryleyb/THKez/3/

EDITTED to make it a bit more complicated - turns out custom rules can't use dependency-expressions the way required can.

Ryley
  • 21,046
  • 2
  • 67
  • 81
  • Except that the function is handling not only DE licenses it does trigger even with NY, which is not supposed to be. is there a way to use if statement ? but really using Regex is very nice in here thanks – Nassim Nov 30 '12 at 18:51
  • Good point - I changed it back to an older version I had made – Ryley Nov 30 '12 at 19:25
  • thanks again, just one last tweak, how can we show the text error only when user TAB to another field or the selected field looses focus or the user submits the form as it is in the default behavior for this module. not a big deal but just to make it look perfect. – Nassim Nov 30 '12 at 20:42
  • That is weird - It really shouldn't be doing anything until you submit the first time... – Ryley Nov 30 '12 at 21:44