[jquery] jQuery Validate Required Select

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.

This question is related to jquery jquery-validate ui-select2

The answer is


<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


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.


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>

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! :)


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>

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;
}

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;
        }
    });

});

use min rule

set first option value to 0

'selectName':{min:1}

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


<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 $

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-validate

Phone Number Validation MVC Jquery Validate custom error message location Jquery validation plugin - TypeError: $(...).validate is not a function JQuery Validate input file type jquery to validate phone number Bootstrap with jQuery Validation Plugin jQuery Validation plugin: validate check box jQuery select box validation Confirm Password with jQuery Validate MVC 4 client side validation not working

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?