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>
4
  • if($('#year option:selected').val() == "0") Commented Feb 15, 2013 at 14:38
  • Are those extra commas typos or errors? Commented Feb 15, 2013 at 14:40
  • @wolvern Thanks ... but its not working. I had checked it with IE but not showing any error in coding..any ideas ? Commented Feb 15, 2013 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 Commented Feb 15, 2013 at 19:33

5 Answers 5

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/

Sign up to request clarification or add additional context in comments.

9 Comments

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, I left both options in the answer for other readers to understand the difference between the two.
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, 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.
@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 ?
|
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

4 Comments

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, 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: stackoverflow.com/questions/14889736/…
@Tom you can use rule {min:1} in that case, no need for custom rule
When using with select2 plugin, it does not focus the right element? why
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);

Comments

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>

4 Comments

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.
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
I meant put the description with your post. So whoever reads it in the future reads the description as well.
description Added. Thanks
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"?

7 Comments

@ Mark Thanks.. The coding seems no mistake but it is not producing correct output (no outputs).
I guess we need to know the exact validation plugin you are using.
It was tagged as such, but I fixed the title to make it more clear.
@ Mark .Not working.. Can u tell which available plugin is best for it. I don't know the name of exact plugin iam using
MarkSchultheiss & Sparky . It working fine while iam setting in this way <option value="">Year</option>. I think our function() in year is not working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.