17

I have following code in jQuery.
I need to display a validation message "Year Required" when the option value of select element is "0".

<script type="text/javascript">
$(document).ready(function () {
   $("#register").validate({
       debug: true,
       rules: {
           year: {
               required: function () {
                   if ($("#year option[value='0']")) {
                       return true;
                   } else {
                       return false;
                   }
               }
           }
       },
       messages: {
           year: "Year Required",
       },
   });
})
</script>

Select box

<select name="year"  id="year">
    <option value="0">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
Tom
  • 500
  • 3
  • 5
  • 16
  • if($('#year option:selected').val() == "0") – Can Feb 15 '13 at 14:38
  • Are those extra commas typos or errors? – Mark Schultheiss Feb 15 '13 at 14:40
  • @wolvern Thanks ... but its not working. I had checked it with IE but not showing any error in coding..any ideas ? – Tom Feb 15 '13 at 14:45
  • Please do not post duplicates, especially when others already posted answers trying to help you: [jQuery select box validations with Validate plugin](http://stackoverflow.com/questions/14889736/jquery-select-box-validations-with-validate-plugin) – Sparky Feb 15 '13 at 19:33

5 Answers5

47

Since you cannot set value="" within your first option, you'll need to create your own rule using the built-in addMethod() method.

jQuery:

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            year: {
                selectcheck: true
            }
        }
    });

    jQuery.validator.addMethod('selectcheck', function (value) {
        return (value != '0');
    }, "year required");

});

HTML:

<select name="year">
    <option value="0">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Working Demo: http://jsfiddle.net/tPRNd/


Original Answer: (Only if you can set value="" within the first option)

To properly validate a select element with the jQuery Validate plugin simply requires that the first option contains value="". So remove the 0 from value="0" and it's fixed.

jQuery:

$(document).ready(function () {

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

});

HTML:

<select name="year">
    <option value="">Year</option>
    <option value="1">1955</option>
    <option value="2">1956</option>
</select>

Demo: http://jsfiddle.net/XGtEr/

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Thanks Sparky.. Its got working now. Yes i know second option but i cannot deduct zero from the option values. Can u explain what is the use of this jsfiddle ? – Tom Feb 16 '13 at 04:51
  • @Tom, I left both options in the answer for other readers to understand the difference between the two. – Sparky Feb 16 '13 at 04:55
  • Jquery is not supported in some old browsers ? If it is like that we need to add server side validations also along with client side scripting ? – Tom Feb 16 '13 at 05:16
  • @Tom, having server-side validation is a backup to protect your database and server since JavaScript validation can be bypassed. It has nothing to do with supporting old browsers. – Sparky Feb 16 '13 at 05:48
  • @Sparkey . Yes i mean if Javascript validations or jquery may not work is some old browsers, it can be bypassed, then server side validation is inevitable ? Is it strict we need to add server side validation also ? – Tom Feb 16 '13 at 06:22
  • @Tom, browser version does not matter to this issue. If you care about what happens to your server, you will always employ server-side validation. This is my last reply as this comments section is not for discussion, let alone an off-topic discussion. – Sparky Feb 16 '13 at 06:30
  • There is one issue i am having. Jquery validation also scrolls you to the exact element when its required and unfilled. but while Its not scrolling me to the `select` element? May be i am using `select2` control with it? can you help me out? – A.J. Mar 18 '14 at 10:48
  • @user570826, do not ask new questions in the comments section. Please review this site's rules and post a new question. – Sparky Mar 18 '14 at 14:47
  • Nice but how can i make it detect select box each time it changes? – Imran Bughio Aug 06 '15 at 14:30
10

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

politus
  • 5,996
  • 1
  • 33
  • 42
  • Thanks .. using empty value will works fine. but i cannot use empty values in my program because it is displaying from an array. for adding empty values just need to use required:true only :) – Tom Feb 15 '13 at 19:02
  • @Tom, you should have mentioned this in your OP and you also should have the courtesy to deal with the answers people already posted on your other question: http://stackoverflow.com/questions/14889736/jquery-select-box-validations-with-validate-plugin – Sparky Feb 15 '13 at 19:35
  • @Tom you can use rule {min:1} in that case, no need for custom rule – politus Feb 18 '13 at 09:23
  • When using with select2 plugin, it does not focus the right element? why – A.J. Mar 19 '14 at 06:20
1

http://docs.jquery.com/Plugins/Validation/Methods/required

edit the code for 'select' as below for checking for a 0 or null value selection from select list

case 'select':
var options = $("option:selected", element);
return (options[0].value != 0 && options.length > 0 && options[0].value != '') && (element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
1

Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<form method="post">
<select name="year"  id="year">
    <option value="0">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<button id="clickme">Click</button>
</form>
<script>
$("#clickme").click(function(){

if( $("#year option:selected").val()=='0'){

alert("Please select one option at least");

  $("#message").html("Select At least one option");

}


});

</script>
  • 2
    A code example is good but i would suggest adding in a little description as to what needs to be done or the answer might be flagged as a very low quality answer. – Syfer Jul 13 '17 at 04:24
  • The code is for Validation of Select box as defined in question. There are two types of Message one is Alert and Another is Print in Div. Please let me know if you need more clarifications. Thanks – Anil chhabra Jul 31 '17 at 07:12
  • I meant put the description with your post. So whoever reads it in the future reads the description as well. – Syfer Jul 31 '17 at 07:16
  • description Added. Thanks – Anil chhabra Jul 31 '17 at 07:41
0

simplify the whole thing a bit, fix some issues with commas which will blow up some browsers:

  $(document).ready(function () {
       $("#register").validate({
           debug: true,
           rules: {
               year: {
                   required: function () {
                       return ($("#year option:selected").val() == "0");
                   }
               }
           },
           messages: {
               year: "Year Required"
           }
       });
   });

Jumping to an assumption, should your select not have this attribute validate="required:true"?

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • @ Mark Thanks.. The coding seems no mistake but it is not producing correct output (no outputs). – Tom Feb 15 '13 at 14:55
  • I guess we need to know the exact validation plugin you are using. – Mark Schultheiss Feb 15 '13 at 15:01
  • It was tagged as such, but I fixed the title to make it more clear. – Sparky Feb 15 '13 at 16:29
  • @ Mark .Not working.. Can u tell which available plugin is best for it. I don't know the name of exact plugin iam using – Tom Feb 15 '13 at 19:10
  • MarkSchultheiss & Sparky . It working fine while iam setting in this way . I think our function() in year is not working – Tom Feb 15 '13 at 19:13
  • This answer does not work... you can't use a function for a `required` rule where the result depends upon itself... http://jsfiddle.net/5RWD3/ – Sparky Feb 15 '13 at 21:31
  • @Tom, [jQuery Validate (aka Validation) plugin](http://docs.jquery.com/Plugins/Validation) is what you appear to be using. It is excellent, you just have to know how to use it. [See my answer](http://stackoverflow.com/a/14903827/594235). – Sparky Feb 15 '13 at 21:51