jQuery validation condition based on elements selection - javascript

I have following input elements on my form and and validation form with jQuery validation plugin.
HTML:
<form name='frmUsers' id='frmUsers' method='post' action='#'>
<div>
<input type='text' name='name' id='name' placeholder='Name' />
</div>
<br />
<div>
<input type='text' name='fixed_budget' id='fixed_budget' placeholder='Fixed budget' />
</div>
<br />
<div>
<select name='budget' id='budget'>
<option value=''>Select your budget</option>
<option value='1000'>1000</option>
<option value='2000'>2000</option>
<option value='3000'>3000</option>
<option value='4000'>4000</option>
</select>
</div>
<br/>
<div>
<input id='save' type='submit' value='Save' />
</div>
</form>
jQuery validation:
$(document).ready(function () {
$("#frmUsers").validate({
onkeyup: false,
onfocusout: false,
ignore: [],
rules: {
"name": {
required: true
},
"fixed_budget": {
required: true
},
"budget": {
required: true
}
},
messages: {
"name": {
required: 'required'
},
"first_name": {
required: 'required'
},
"last_name": {
required: 'required'
}
},
errorPlacement: function (error, element) {
},
submitHandler: function () {
return false;
}
});
});
Now all elements are required fields but I have specific condition on Fixed budget (text box) and budget (select box).
For example:
When user click on submit, fixed budget and budget elements display with errors but (1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
Here is my working JSFiddle: http://jsfiddle.net/mananpatel/85KR4/384/
Any Idea?
Thanks.

(1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
In other words, you only require one of those two fields filled out.
Include the additional-methods.js file and use the require_from_group method.
rules: {
name: {
required: true
},
fixed_budget: {
require_from_group: [1, ".requiredGroup"]
},
budget: {
require_from_group: [1, ".requiredGroup"]
}
},
DEMO: http://jsfiddle.net/7om97gk8/
Note:
Use return false within the errorPlacement function if you want to suppress messages. Don't leave the function empty, as that's sloppy coding.
errorPlacement: function (error, element) {
return false;
},
Also, use the latest version of the plugin file as this will ensure the require_from_group method operates bug-free.
I don't understand why you are using the messages option when you've totally disabled these messages from displaying. You can safely remove messages in this case.

Related

jQuery: Prevent Select List from turning green on select

This is probably pretty strange but I have a form page with various elements that are being checked for validation when I hit submit. Unfortunately I also have a management side of the page that performs its own Ajax actions.
One of these items has a select list that when I select an option it turns green. I don't really need/want the green validation on this select list as it isn't tied to my postback action at all.
Any ideas on how to turn it off with jQuery? (I'm currently just using $("#form").validate({ ... ...}) to validate my other fields and I think it is taking over for this element too)
Current Validation:
$(function () {
// Validation
$("#edit-opp-prod-form").validate({
// Rules for form validation
rules: {
Opportunity: {
required: true
},
CommissionAmount: {
required: true,
currency: ["", false]
}
},
// Messages for form validation
messages: {
Opportunity: {
required: "An Opportunity name is required."
},
ComissionAmount: {
required: "A Commission Amount must be set."
}
},
// Do not change code below
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
The Select List I don't want to be validated,
<section class="col col-5">
<div>
#Html.Label("ProductID", "Products", new { #class = "label" })
#Html.Action("ProductSelectList", "Products", new { unmappedProducts = true})
</div>
</section>
This produces this when I inspect,
<select id=ProductID" name="ProductID">Products</label>
<option value="...">...</option>
...
<option value="...">...</option>
</select>

Jquery validation plugin errorplacement for single element

i am using Jquery validation plugin for validating the form.when validating the form for one element alignment is not proper.
If you see the image,for the city field icon + button alignment not proper when it validating the form. Because label error validation is displaying in between the input element and icon +. I need to display the error message below of the element.
My html code is like this for the city field
<tr>
<td align="right"><span class="mandetry">*</span> City:</td>
<td>
<div class="input-group" id="app_details">
<input type="text" class="form-control client_city" name="client_city" id="city_name" value="<?php echo set_value('client_city')?>">
<span class="input-group-btn">
<a class="btn btn-default" id='addnewcity' href="<?php echo base_url('addnewcity')?>"><i class="fa fa-plus-square"></i></a>
</span>
<div id="messageBox"></div> <!-- Here i would like to display message-->
</div> </tr>
js code is like this
$(document).ready(function(){
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name:{required:true},
client_address:{required:true},
client_city:{required:true},
errorPlacement: function(error, element) {
if (element.attr("name") == "client_city" )
{
error.appendTo("#messageBox");
}
}
},
messages: {
client_name:{required:"The Client name is a required / mandatory field"},
client_address:{required:"The Client address is a required / mandatory field"},
client_city:{required:"The City is a required / mandatory field"},
}
});
});
Error message not appended to messageBox div.Is there any wrong with errorPlacement in js. For only city element i need to display the error message properly. For other form fields it shouldn't change.i am unable to solve this issue. Please suggest me. Thanks.
You are missing the else part, if it is not the client_city element then you need to insert the error after
$(document).ready(function () {
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name: {
required: true
},
client_address: {
required: true
},
client_city: {
required: true
}
},
errorPlacement: function (error, element) {
console.log('dd', element.attr("name"))
if (element.attr("name") == "client_city") {
error.appendTo("#messageBox");
} else {
error.insertAfter(element)
}
},
messages: {
client_name: {
required: "The Client name is a required / mandatory field"
},
client_address: {
required: "The Client address is a required / mandatory field"
},
client_city: {
required: "The City is a required / mandatory field"
},
}
});
});
Demo: Fiddle

JQuery Validation - radio button required for text input

I have two radio buttons and a text input. I want one of the radios required for the text input to be then validated. I can disable the text input field unless selected, but I think it would be more user intuitive to allow text input first, and only error if they don't also select a radio.
The form is giving me back an error that the radios are required, but I don't want the remote check to kick in unless one of the radio buttons is selected.
So here's what I have...
JQuery:
jQuery( "#modalform" ).validate({
onkeyup: false,
onfocusout: false,
rules: {
'register_domain[]': {
required: true
},
chosen_domain: {
required: true,
minlength: 4,
remote: {
url: "check.php",
type: "post",
data: {
register_domain: function() {
return jQuery('input[name="register_domain[]"]');
}
}
}
}
},
messages: {
'register_domain[]': {
required: "Choose one"
},
chosen_domain: {
required: "Required input",
minlength: jQuery.validator.format("Please, at least {0} characters are necessary"),
remote: jQuery.validator.format("Invalid domain name: {0}")
}
}
});
Form Fields:
<label class="radio-inline">
<input type="radio" name="register_domain[]" id="own_domain" value="owned"> Own Domain
</label>
<label class="radio-inline">
<input type="radio" name="register_domain[]" id="new_domain" value="new"> Register Domain
</label>
<label for="register_domain[]" class="error" style="display:none;">Please choose one.</label>
<input type="text" size="50" placeholder="www." id="inputDomain" name="chosen_domain" class="form-control required" required="required">
Quote OP:
"I don't want the remote check to kick in unless one of the radio buttons is selected."
You can use the rules('add') and rules('remove') methods to toggle the remote rule within an external change handler...
$('input[name="register_domain[]"]').on('change', function() {
if ($(this).val() == "owned") {
$('input[name="chosen_domain"]').rules('remove', 'remote');
} else {
$('input[name="chosen_domain"]').rules('add', {
remote: {
url: "check.php",
type: "post",
data: {
register_domain: function() {
return jQuery('input[name="register_domain[]"]');
}
}
}
});
}
});

JQuery Validation - Checkbox validation not posting all values

I'm having problems with some checkbox validation.
I'm using the plugin validation for this: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have three checkboxes and at least one must be ticked. My initial form code for these checkboxes are:
<input type="checkbox" checked name="check_options" value="News">News
<input type="checkbox" checked name="check_options" value="Events">Events
<input type="checkbox" checked name="check_options" value="Promotions">Promotions
The validation rules are:
$("#commentForm").validate({
rules: {
email_options_name: {
required: true
},
email_options_company: {
required: true
},
email_options_country: {
required: true
},
email_option_email: {
required: true,
email: true
},
check_options: {
required: true,
minlength: 1
}
},
});
The validation here for check_options works fine. However the php script which processes the form will only print the value of the last check box (so if two or three were ticked only the last value is posted).
I revised my input names to fix this:
<input type="checkbox" checked name="check_options[]" value="News">News
<input type="checkbox" checked name="check_options[]" value="Events">Events
<input type="checkbox" checked name="check_options[]" value="Promotions">Promotions
This shows all of the values in the post. However I can't get the validation to work for it. If I put in my rules:
check_options[]: {
required: true,
minlength: 1
}
I get an Javascript error: SyntaxError: missing : after property id
If i leave it without the square brackets the validation doesn't happen.
Thanks for any help!
Use HTML like this:
<input type="checkbox" checked name="check_options[]" value="News" required minlength="1">News
<input type="checkbox" checked name="check_options[]" value="Events">Events
<input type="checkbox" checked name="check_options[]" value="Promotions">Promotions
and the javascript-
check_options: {
required: true,
minlength: 1
}

Attaching jquery validation in .post works but not in .get

I am using jquery validate plugin to validate dynamically loaded form. For some cases I'm loading the content using $.post and in the callback I call a function that adds the validation rules. That works. For some content, I am using $.get and in that callback I am also calling a function that adds the validation rules. However, when using $.get the form is not validated at all.
What is my problem? Is there really any kind of difference using post and get in this perspective?
I think this is the significant code but I did add a lot of code after this in case it's needed. This is where I call the function that adds the validation rules:
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid }, function(data){
//Now, add the validation rules:
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
This is the code loading the form:
$("#agents td").live('click',function(event)
{
//alert("Agents");
event.preventDefault();
var col = $(this).parent().children().index($(this));
var $td= $(this).closest('tr').children('td');
var $agentid=$td.eq(2).text();
var $name=$td.eq(3).text();
if(col==0){
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid }, function(data){
//alert("GETDONE");
//Now, add the validation rules:
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
});
//and the rest of the code
//.
//.
Here is the function for adding the validation rules:
function addUpdateAgentValidation(){
//alert("GETDONE 2");
$("#updateagentform").validate({
errorContainer: "#updateagentmessagebox",
errorLabelContainer: "#updateagentmessagebox ul",
wrapper: "li", debug:true,
rules: {
email1: {// compound rule
// required: true,
email: true
},
email2: {
// required: true,
equalTo: "#email1"
},
username: {
// required: true,
remote: "http://localhost/SMICAdmin/smicsoap/soap_is_agentusername_available.php"
},
password: {
// required: true
},
password2: {
//required: true,
equalTo: "#password1"
}
},
messages: {
email1: {// compound rule
email: "Korrekt emailadress saknas"
},
email2: {
equalTo: "Mailadresserna matchar inte varandra"
},
//username: "Anv‰ndarnamnet mÂste vara unikt"
username: {
remote: "Användarnamn finns redan"
},
password2: {
equalTo: "Lösenord inte lika"
}
}
});
};
And this is where where I post the form:
$("#updateagentform").live("submit", function(e){
//Prevent the form from submitting normally
// alert("Trying to submit user update");
e.preventDefault();
$.post("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php",$(this).serialize(),function(msg){
//alert the response from the server
//alert(msg);
$("#dialog-modal").dialog("close");
});
$("#usertable").empty();
$('#usertable').load("http://localhost/SMICAdmin/adminactivities/admin_load_agents.php");
$("#modalarea").empty();
$('#modalarea').css("visibility","hidden");
});
And the code generating the form:
echo "<div class='errormessage' id='updateagentmessagebox'>
<ul></ul>
</div>
<form id='updateagentform' method='post'>
Ändra önskade fält<br/>
* Förnamn: <input type='text' name='firstname' /> <br/>
* Efternamn: <input type='text' name='surname' /> <br/>
* Email: <input id='email1' type='text' name='email1' /> <br/>
* Repetera email: <input id='email2' type='text' name='email2' /> <br/>
* Användarnamn: <input id='username_ID' type='text' name='username' /><br/>
* Lösenord: <input id='password1' type='text' name='password' /><br/>
* Repetera lösenord: <input id='password2' type='text' name='password2' /><br/>";
foreach ($roles as $key=>$role) {
if(in_array($key, $role_ids)){
echo "<input type='checkbox' name='rid".$key."' value='rid".$key."' checked />".$role."<br/>";
}else{
echo "<input type='checkbox' name='rid".$key."' value='rid".$key."' />".$role."<br/>";
}
}
echo "<input id='submitupdateagentform' type='submit' value='Uppdatera agent' /></form>";
What is my problem and how do I fix it?
You're calling .validate() on a form that doesn't exist on the page yet.
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid },
function(data){
// form does not exist in DOM here
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
// form exists after this line.
$("#dialog-modal").html(data).dialog("open");
});
You need to rearrange your function call so that .validate() gets called after the form gets appended to the DOM:
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid },
function(data){
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
addUpdateAgentValidation();
});

Categories