162

I am trying to validate html select element using jQuery Validate plugin. I set "required" rule to true but it always passes validation because zero index is chosed by default. Is there any way to define empty value that is used by required rule?

UPD. Example. Imagine we have the following html control:

<select>
  <option value="default">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

I want Validation plugin to use "default" value as empty.

SiberianGuy
  • 24,674
  • 56
  • 152
  • 266

11 Answers11

247

An easier solution has been outlined here: Validate select box

Make the value be empty and add the required attribute

<select id="select" class="required">
<option value="">Choose an option</option> 
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
Community
  • 1
  • 1
Andrew Coats
  • 2,627
  • 1
  • 15
  • 5
  • 12
    But you have to give your option an empty value - not always possible or wishable – Muleskinner Oct 11 '12 at 11:42
  • 4
    This shouldn't be the accepted answer because the original poster is specifically asking to use "rules" which is an option that is fed to the validate constructor, and not present in markup. Sometimes you do not have the luxury of modifying the markup. (And personally, I just prefer not to to put logic in markup.) – Mason Houtz Nov 13 '12 at 02:32
  • 4
    @MasonHoutz it's still logic in the markup, whether the logic expects value="" or value="default" – billrichards Jan 23 '14 at 22:16
227

You can write your own rule!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg !== value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });
user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
JMP
  • 7,734
  • 6
  • 33
  • 34
  • 2
    You can test the selected text instead of value, like this: `$.validator.addMethod("valueNotEquals", function(value, element, arg){ return return arg != jQuery(element).find('option:selected').text(); }, "Value must not equal arg.");` – Pablo S G Pacheco Jan 08 '14 at 21:45
  • 12
    To help future readers: Where is says SelectName it does mean the value of the name attribute and not the value of the id attribute. This is a bit confusing since when working in JS one usually works with the id and not the name. See documentation [here](http://jqueryvalidation.org/validate): "rules (default: rules are read from markup (classes, attributes, data)) Type: Object Key/value pairs defining custom rules. Key is the **name** of an element" – Dror Mar 03 '14 at 18:47
46

the most simple solution

just set the value of the first option to empty string value=""

<option value="">Choose...</option>

and jquery validation required rule will work

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
33

use min rule

set first option value to 0

'selectName':{min:1}
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Funky Dude
  • 3,867
  • 2
  • 23
  • 33
9

You only need to put validate[required] as class of this select and then put a option with value=""

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>
Matt
  • 45,022
  • 8
  • 78
  • 119
omalave
  • 775
  • 1
  • 8
  • 15
8

I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)

  • 1
    in short, add `required` attribute to the ` – Stephen May 04 '15 at 22:04
6
<select class="design" id="sel" name="subject">
   <option value="0">- Please Select -</option>
   <option value="1"> Example1 </option>
   <option value="2"> Example2 </option>
   <option value="3"> Example3 </option>
   <option value="4"> Example4 </option>
</select>
<label class="error" id="select_error" style="color:#FC2727">
   <b> Warning : You have to Select One Item.</b>
</label>
<input type="submit" name="sub" value="Gönder" class="">

JQuery :

jQuery(function() {  
    jQuery('.error').hide(); // Hide Warning Label. 
    jQuery("input[name=sub]").on("click", function() {
        var returnvalue;
        if(jQuery("select[name=subject]").val() == 0) {
            jQuery("label#select_error").show(); // show Warning 
            jQuery("select#sel").focus();  // Focus the select box      
            returnvalue=false;   
        }
        return returnvalue;
    });
});  // you can change jQuery with $
Farukest
  • 1,498
  • 21
  • 39
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

 <form id="myform"> 
       <select class="form-control" name="user_type">
        <option value="">Select</option>
        <option value="2">1</option>
        <option value="3">2</option>
        </select>
       </form>


<script>
  $('#myform').validate({ // initialize the plugin
            rules: {
          user_type:{ required: true},
         }
      });
</script>

select value will be blank

abhishek kumar
  • 448
  • 4
  • 10
  • 2
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Filnor Nov 30 '18 at 12:48
2

The solution mentioned by @JMP worked in my case with a little modification: I use element.value instead of value in the addmethod.

$.validator.addMethod("valueNotEquals", function(value, element, arg){
    // I use element.value instead value here, value parameter was always null
    return arg != element.value; 
}, "Value must not equal arg.");

// configure your validation
$("form").validate({
    rules: {
        SelectName: { valueNotEquals: "0" }
    },
    messages: {
        SelectName: { valueNotEquals: "Please select an item!" }
    }  
});

It could be possible, that I have a special case here, but didn't track down the cause. But @JMP's solution should work in regular cases.

Legends
  • 21,202
  • 16
  • 97
  • 123
1

It's simple, you need to get the Select field value and it cannot be "default".

if($('select').val()=='default'){
    alert('Please, choose an option');
    return false;
}
Maycow Moura
  • 6,471
  • 2
  • 22
  • 19
0

how to validate the select "qualifica" it has 3 choose

$(document).ready(function(){

    $('.validateForm').validate({
        rules: {
            fullname: 'required',
            ragionesociale: 'required',
            partitaiva: 'required',
            recapitotelefonico: 'required',
            qualifica: 'required',
            email: {
                required: true,
                email: true
            },
        },
        submitHandler: function(form) {

            var fullname = $('#fullname').val(),
                            ragionesociale = $('#ragionesociale').val(),
                            partitaiva = $('#partitaiva').val(),
                            email = $('#email').val(),
                            recapitotelefonico = $('#recapitotelefonico').val(),
                            qualifica = $('#qualifica').val(),
                            dataString = 'fullname=' + fullname + '&ragionesociale=' + ragionesociale + '&partitaiva=' + partitaiva + '&email=' + email + '&recapitotelefonico=' + recapitotelefonico + '&qualifica=' + qualifica;

            $.ajax({
                type: "POST",
                url: "util/sender.php",
                data: dataString,
                success: function() {

                    window.location.replace("./thank-you-page.php");


                }
            });
            return false;
        }
    });

});
Kamalesh M. Talaviya
  • 1,422
  • 1
  • 12
  • 26
  • 3
    Welcome to Stack Overflow! Thank you for this code snippet, which might provide some limited short-term help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Toby Speight Jan 31 '18 at 13:27