Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation on select box not working

I am using jQuery validation plugin for client side validation, but my validation does not work on my select box.

HTML

<select id="select" class="required">
    <option value="-1">Choose</option>
    <option value="child">test2</option>
</select>

JavaScript

$("#formid").validate({
    select: {
        required: function(element) {
            if ($("#select").val() == '-1') {
                return false;
            } else {
                return true;
            }
        }
    }
}); 

How do I get this working?

like image 512
Surinder ツ Avatar asked Dec 19 '12 04:12

Surinder ツ


2 Answers

A simple way to fix this problem is to give the non valid option the value of "". Then simply call validate on your form and it will not submit when "Choose" is selected.

HTML

<form id="formid">
    <select name="select" class="required">
        <option value="">Choose</option>
        <option value="child">test2</option>
    </select>

    <input type="submit" />
</form>​

JavaScript

$("#formid").validate(); ​

Demo

like image 124
3dgoo Avatar answered Oct 13 '22 04:10

3dgoo


Although this probably works with some of the aforementioned methods,if you're looking to use a custom validation function, you should use addMethod as documented here: http://docs.jquery.com/Plugins/Validation/Validator/addMethod

So you would first add the method through something like

$.validator.addMethod("requiredSelect", function(element) {
                return ( $("#select").val() !='-1' );
            }, "You must select an option.");

Then simply assign the validator with

$("#formid").validate({
  rules: {
    select: { requiredSelect : true }
  }
});
like image 34
Cameron Bielstein Avatar answered Oct 13 '22 05:10

Cameron Bielstein