jQuery Validate Required Select

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.





Put some snippet of code so we can help.
– Lee
May 24 '10 at 23:55





possible duplicate: stackoverflow.com/questions/1271640/jquery-validate-select-box
– cregox
Mar 11 '11 at 21:15




11 Answers
11



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!"

);





it helped me too, thanks
– I-M-JM
Dec 6 '10 at 8:31





Saved my day! Thanks.
– Rui Marques
May 26 '12 at 15:56





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 8 '14 at 21:45



$.validator.addMethod("valueNotEquals", function(value, element, arg) return return arg != jQuery(element).find('option:selected').text(); , "Value must not equal arg.");





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: "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 3 '14 at 18:47






Best solution so far!
– digz6666
Jul 17 '15 at 1:07



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>





This is a great answer and I'm shocked that it isn't the accepted one
– Mark Withers
Jul 27 '12 at 14:58





this one should be an accepted one. You don't have to write your own method. DRY
– nXqd
Sep 6 '12 at 7:55





But you have to give your option an empty value - not always possible or wishable
– Muleskinner
Oct 11 '12 at 11:42






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 2:32





@MasonHoutz it's still logic in the markup, whether the logic expects value="" or value="default"
– billrichards
Jan 23 '14 at 22:16



the most simple solution



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


value=""


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



and jquery validation required rule will work


required


will work





Indeed the most simple one
– ehh
Dec 31 '16 at 6:41





This did not work for me
– dougajmcdonald
Aug 7 '17 at 15:47





Cool, the simplest solution for me.
– HamasN
Dec 19 '17 at 2:10



use min rule



set first option value to 0


'selectName':min:1





The first value is fixed (there is some backend logic against this value)
– SiberianGuy
May 25 '10 at 1:23





Great! SIMPLE! :-D
– curly_brackets
May 5 '11 at 11:57





great hack funky
– Desert P
Feb 11 '16 at 12:28



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


validate[required]



for example:


<select class="validate[required]">
<option value="">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>





This is work for me. Thanks
– Narendra Verma
Sep 28 '17 at 13:40



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:



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



<select name="myselect">


<select name="myselect">



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>


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



or



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


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



Set the plugin validation rule



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

);


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

);



or



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


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





Thank you for consolidating the answer here. Very helpful
– Christina
Dec 2 '14 at 19:49





=== THIS IS THE MOST CONCISE AND MINIMALISTIC ANSWER ===
– Stephen
May 4 '15 at 22:02





in short, add required attribute to the <select> tag and add disabled attribute to the first <option> tag (or the one with the selected attribute if there is one)
– Stephen
May 4 '15 at 22:04


required


<select>


disabled


<option>


selected



Here is the simple and understandable example :


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

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



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


element.value


value


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.



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;

);



);





Welcome to Stack Overflow! Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve 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 at 13:27


html
<select class="design" id="sel" name="subject">
<option >- 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><td>

<input type="submit" name="sub" value="Gönder" class="">
**jQuery**

$(document).ready(function()
if($("#sel").val() == null)
alert('select a value)

);





That does not look good - why do you fire an alert on loading the page, but not check for that before submitting the form?
– Nico Haase
Aug 25 at 9:54






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)