I am using jQuery validation plugin for client side validation, but my validation does not work on my select box.
HTML
<select id="select" class="required">
<option value="-1">Choose</option>
<option value="child">test2</option>
</select>
JavaScript
$("#formid").validate({
select: {
required: function(element) {
if ($("#select").val() == '-1') {
return false;
} else {
return true;
}
}
}
});
How do I get this working?
A simple way to fix this problem is to give the non valid option the value of "". Then simply call validate on your form and it will not submit when "Choose" is selected.
HTML
<form id="formid">
<select name="select" class="required">
<option value="">Choose</option>
<option value="child">test2</option>
</select>
<input type="submit" />
</form>
JavaScript
$("#formid").validate();
Demo
Although this probably works with some of the aforementioned methods,if you're looking to use a custom validation function, you should use addMethod as documented here: http://docs.jquery.com/Plugins/Validation/Validator/addMethod
So you would first add the method through something like
$.validator.addMethod("requiredSelect", function(element) {
return ( $("#select").val() !='-1' );
}, "You must select an option.");
Then simply assign the validator with
$("#formid").validate({
rules: {
select: { requiredSelect : true }
}
});
For some reason no solution provided worked in my case, it boiled down to jQuery Validate calling the "optional" check on the value of the drop down, which that called the !required rule.
When the select box selected an empty value, the required showed "false" which inverted meant it was always optional when the required failed, so it never ran the required rule.
I overwrote the optional function with the below, which returned "False" on optional if it was a required item:
// Get Select to work
$.validator.prototype.optional = function (element) {
var val = this.elementValue(element);
// Custom logic to get Select to show validate when value is empty
if (element.nodeName.toLowerCase() === "select") {
if (element.hasAttribute("data-val-required") || element.hasAttribute("required")) {
return false;
}
}
return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
};
instead of:
$("#select").val()
try:
$("#select :selected").val()
$("#select").val() returns all the option values instead of the selected one.
Here, my assumption is that you want to check if the user has chosen the option -1 when the control report-crime is validated.
by default
<option value="">Choose</option>
works with
required: true
There is missing name attribute in your select element.
In my case that was the issue since the jQuery Validatation Plugin looks for the name not id while validating.
Related
How can I change the default Message of a required select option field. Its a variation of WooCommerce's product. I added the property dynamically and try to change the message my bellow code able to change the message but it not works . It always appearing no matter if there is a selected value or not.
JsFiddle
HTML
<select id="color" class="" name="attribute_color" data-attribute_name="attribute_color">
<option value="" selected="selected">Choose an option</option>
<option value="White" class="attached enabled">White</option>
<option value="Black" class="attached enabled">Black</option>
</select>
Script
jQuery(document).ready(function($) {
$('select#color').prop('required', true);
if( !$('select#color').has('value').length > 0 ) {
$('select#color').attr("oninvalid", "this.setCustomValidity('Please select a color')");
}else{
$('select#color').removeAttr("oninvalid", "this.setCustomValidity('Please select a color')");
}
});
JsFiddle
From the msdn docs:
Constraint API's element.setCustomValidity()
The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.
It means that once you setCustomValidity error the input will be considered as invalid till you wont reset it by passing empty string.
What I did below is checking when select event happened and check if select has value if it doesn't then set error if it has then reset error.
FIDDLE
jQuery(document).ready(function($) {
var selectColor = $('select#color');
selectColor.prop('required', true);
/* Check if there is no selected value on ready if not mark select as invalid */
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}
/* Do the same check when select value changed */
selectColor.on('change', function(){
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}else{
selectColor[0].setCustomValidity('');
}
})
});
Try this one
$('select#color').on('invalid', function () {
return this.setCustomValidity('Please select a color.');
}).on('change', function () {
return this.setCustomValidity('');
});
I'm looking for a way to have JQuery validate plugin check the value of a selected option's data element to determine if the selection is valid or invalid. The reason invalid options need to be included in the select is primarily for display purposes. i.e. if I have a select with the question "What colour is your house?" and I have options "Red", "Blue", "Green", the end user needs to be explicitly shown that "Green" is not a valid choice.
Right now I'm using 'validate' for everything else but I had to write in a separate function to check these fields and I'd like to be able to do it all with just 'validate'.
Here is a more detailed example of what I'm looking for:
HTML:
<html>
<head>
<script type="text/javascript" src="./js/jquery-validate-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
// BASIC VALIDATION
// Set Validator Defaults and rules
$.validator.setDefaults({
errorPlacement: function(error, element) {
$(element).attr({"title": error.append()});
},
highlight: function(element){
$(element).addClass("error");
},
unhighlight: function(element){
$(element).removeClass("error");
}
});
$("#myform").validate({
rules: {
email: {
required: true,
email: true
},
myselect: {
// HOW DO I DEFINE THIS RULE SO THAT
// IF OPTION 3 IS SELECTED THIS RETURNS
// INVALID
}
}
});
});
</script>
</head>
<body>
<form id='myform' name='myform'>
<input type='text' id='email' name='email value='' />
<select id='myselect' name='myselect'>
<option id='1' data-is_valid='1'>Option 1</option>
<option id='2' data-is_valid='1'>Option 2</option>
<option id='3' data-is_valid='0'>Option 3</option>
<option id='4' data-is_valid='1'>Option 4</option>
</select>
</form>
Quote OP:
"I had to write in a separate function to check these fields and I'd like to be able to do it all with just validate."
You could use the .addMethod() method to wrap your separate function and turn it into a rule.
However, if you'd take the time to explain why you'd want to restrict a select to certain options, when you're already in control of how the select is created in the first place, a better answer or workaround could possibly be suggested. (this is one way that SO benefits everyone else long after the OP is satisfied)
Here's how I ended up solving it:
Thankyou to Sparky for pointing me in the right direction
jQuery.validator.addMethod("valid_option", function(value, element) {
if ($(":selected", element).data('is_valid') == "1") {
return true;
}
return false;
}, "  Error, Invalid Selection");
I have problem with Mootools formcheck js when applying custom function to Selectbox field. Custom Function will be work fine with Text Field, but Selectbox is NOT.
My dummy code of Custom Function:
var customFunc = function customFuncF(el) {
el.errors.push('Custom function!!!');
return false;
};
And There are a simple form that I apply to a text field:
and
<input type="text" class="validate['%customFunc']" id="User_lastName" name="User[lastName]" >
-> It works fine with text field.
But when I apply custom function to Selectbox field, example as Office list in my simple form, it's seems not work and always returns true. My example code for Selectbox
<select id="User_officeId" class="validate['%customFunc']" name="User[officeId]" >
<option selected="selected" value="">-Select Office-</option>
<option value="1">Office A</option>
<option value="2">Office B</option>
</select>
How can I apply custom function to Selectbox field?
Thanks,
It was caused by your validate which excludes the keyword 'required'. In fact, the custom function works.
But in function 'manageError':
manageError : function(el, method) {
...
} else if ((isValid || (!el.validation.contains('required') && !el.value))) {
this.removeError(el);
return true;
}
return true;
},
As no 'required' and no value in here, the pushed error was be removed. :(
You can add the word 'required' into validate[] or setup the value of first option to 0 instead of blank.
i am using select option through Struts HTML tags for a particular jsp. The values of the option are Yes and No. Here is the code.
<select name="select" id='choice'>
<option value="<%YES%>" selected><%="YES"%></option>
<option value="<%=NO%>"></option>
The value seen in the select option list by default will be YES.
I am performing validation such that if no value is selected(as Selected property given on 'YES') and form is submitted, a alert should be thrown to select new value. Below is my code.
if( document.form.select.value == "YES" )
{
alert( "Please select other value" );
return false;
}
if( document.form.select.value == "NO" )
{
alert( "Please select other value" );
return false;
}
The above code is not validating properly. Can anyone suggest me some changes.
Thanks
This is how to check if the selected value is the default value, even though I am not understanding very well your intentions.
el = document.getElementById('choice');
if( el.options[el.selectedIndex].defaultSelected){
alert("Please select other value");
return false;
}
PS: you probably need to fix your code :
<select name="select" id='choice'>
<option value="<%=YES%>" selected><%="YES"%></option>
<option value="<%=NO%>"></option>
</select>
I have 2 select boxes on a page with a variable number of options in them.
For instance:
<fieldset>
<label for="fizzwizzle">Select a Fizzwizzle</label>
<select name="fizzwizzle" id="fizzwizzle" size="10">
<option>Fizzwizzle_01</option>
<option>Fizzwizzle_02</option>
<option>Fizzwizzle_03</option>
<option>Fizzwizzle_04</option>
</select>
</fieldset>
<fieldset>
<label for="fizzbaggot">Select a Fizzbaggot</label>
<select name="fizzbaggot" id="fizzbaggot" size="10">
<option>Fizzbaggot_01</option>
</select>
</fieldset>
I would like to verify that both of these select boxes have a selected option. My initial thought is to simply use JQuery but I can't seem to figure out how to do that. My attempts so far have been futile but I have the following code that I think should work with the missing link.
function verify_selectboxen_selection() {
var allSelected = true;
$('select').each(function() {
/* if select box doesn't have a selected option */
allSelected = false;
break;
});
if (!allSelected) {
alert('You must select a Job and a Disposition File.');
}
return allSelected;
}
Seems simple enough. Thoughts?
In jQuery you can use the :selected selector to get the total options selected. This number out to match the number of select's themselves:
if ($("select").length === $("option:selected").length) {
// they match
}
I would like to verify that both of these select boxes have a selected option
It's not possible for a (non-multiple) select box not to have a selected option! If you don't declare selected on one of the options, the browser will automatically select the first option.
So: return true; :-)
If you want to have an ‘unselected’ initial state, you'd have to include a no-option option for it, usually the first one:
<select name="fizzbaggot">
<option value="" selected="selected">(Select a fizzbaggot)</option>
<option>foo</option>
<option>baz</option>
<option>bar</option>
</select>
Then you can check whether a different option to that one has been selected, either by saying:
$('select').each(function() {
if ($(this).val()!=='')
allSelected= false;
});
Or, if you might want to use the empty string as a valid value, you can just look at the index of the selected option:
$('select').each(function() {
if (this.selectedIndex===0)
allSelected= false;
});
You can use the :selected selector for this.
var unselected = []
$('select').each(function(){
if (0 == $(this).find('option:selected').length) {
unselected.push(this.id);
}
});
if (unselected.length != 0) {
// unselected contains the ids of non-selected select boxes
}
Or you could check their values with val(). This presumes that you have a default option with no value (ie empty string value).
var unselected = []
$('select').each(function(){
if ('' == $(this).val()) {
unselected.push(this.id);
}
});
if (unselected.length != 0) {
// unselected contains the ids of non-selected select boxes
}
function checkSelects() {
return $("select :selected").length == $("select").length;
}
alert(checkSelects());