Minimum collective value of several inputs with jquery validate - javascript

I have several text inputs with the same name and I'm trying to prevent the form from submitting if the collective value of all the inputs is less than 1. E.g. the user can't put 0 on all of them, but must at least put 1 on one of them so the collective value of all inputs is at least 1.
I have created a method in jquery validate to check if the value is greater than 0 of the selected inputs
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]"></td>
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]"></td>
This is the method:
$.validator.addMethod("nbTeams", function(value, elem, param) {
return $(".nbTeamsVal").value > 0;
},"Collective value must be more than 1!"
);
This is my rule and custom message
$(document).ready(function () {
$('#myForm').validate({
rules: {
"nbTeams[]":{
required: true
}
},
messages: {
"nbTeams[]":"This group of fields can only contain numbers and one must contain a value of at least 1."
},
errorElement : 'div',
errorLabelContainer: '.errorTxt',
submitHandler: function (form) {
form.submit();
}
});
});

i edit your code try this :
$.validator.addMethod("nbTeams", function(value, elem) {
var sumOfVals = 0;
$(".nbTeamsVal").each(function () {
sumOfVals = sumOfVals + parseInt($(this).val());
});
return sumOfVals>0;
},"Collective value must be more than 1!"
);
$('#myForm').validate({
rules: {
"nbTeams[]":"nbTeams"
},
errorElement : 'div',
errorLabelContainer: '.errorTxt',
submitHandler: function (form) {
alert('valid form submitted'); // for demo
return false; // for demo
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="myForm" method="post" action="#">
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]" value="0"></td>
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]" value="0"></td>
<div class="errorTxt"></div>
<button type="submit">Submit</button>
</form>

Related

How to pass dynamic value to jquery validation function

I have a form which have some dynamically added input,
Here i input have total_amt = 100;
How can i, form should not submit until, sum of all the dynamically added inputs must be equal to total_amt
Here is my code.
$(function(){
var i = 1;
$('#add_more').click(function(event) {
event.preventDefault();
$('input.items').last().attr('name', 'item['+i+']');
$('#cart_items').append($('#tmp_cart').html());
$('input[name="item['+i+']"]').rules("add", {
required: true,
depositsSum : function(){
return $(this).val();
},
messages:'Sum of total items should be equal to 100',
});
i++;
});
$.validator.addMethod("depositsSum", function(value, element, params)
{
var amnts = 0;
$(params[0]).each(function() {
amnts += parseFloat($(this).val());
});
return amnts;
});
$("#myForm").validate({
rules: {
'item[0]': {
required:true
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<form action="" method="POST" id="myForm">
Total Items<input type="text" value="100" name="total_amt" id="total_amt">
<div id="cart_items">
Items<input type="text" name="item[0]" class="items"><br/>
</div>
<button id="add_more">Add More</button>
<input type="submit" name="submit" value="submit">
</form>
<div id="tmp_cart" style="display: none;">
<label>
Items<input type="text" name="item[]" class="items">
</label><br/>
</div>
Two flaws in your code...
Within your .rules() method:
depositsSum : function(){
return $(this).val();
},
You're trying to set the parameter of you custom rule to the value of the field. This is complete nonsense. A parameter is something like Max: 10, where 10 is the parameter and it defines the rule; it's never the actual value of the field, which, by the way, always changes and is empty when the page loads. When you want to invoke the custom rule, set the parameter to true.
And related to the next problem...
Within your .addMethod() method:
$(params[0]).each(function() {
amnts += parseFloat($(this).val());
});
The params argument would be useless in your case, since the parameter can not be used for passing the dynamic values of other fields. Use a jQuery selector to grab the other fields. Since the name begins with item, use the "starts with" selector.
$('[name^="item"]').each(function() {
amnts += parseFloat($(this).val());
});

jQuery Validator Add method not working

I'm using jquery validator addmethod for validation. While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.
HTML Code:
<div class="container">
<div class="lg_cont">
<h2>Reset your Password</h2>
<form method="post" class="lg_form" name="lg_form" id="formresetpwd">
<p class="lg_inp"><label for="pwd">Password <span>*</span></label>
<!--<span><i class="fa fa-lock"></i></span>-->
<input type="password" name="pwd" id="pwd" class="txt"/>
</p>
<p class="lg_inp">
<label for="lg_pass">Retype Password <span>*</span></label>
<!--<span><i class="fa fa-lock"></i></span>-->
<input type="password" name="rpwd" id="rpwd" class="txt"/>
</p>
<p><label style="font-size:13px;" id="psw_hint" class="hint" for="psw_hint"><span>*</span>Password should atleast contain 6 characters with Alphabet, Numeric and Underscores.</label></p>
<p><button type="submit" class="btn btn-success btn-md">Submit</button></p>
<?php if (isset($msg)) { ?>
<p><?php echo $msg; ?></p>
<?php } ?>
</form>
</div>
</div>
Jquery:
$('.btn-md').on('click', function () {
alert('test');
$('#formresetpwd').validate({
rules: {
pwd: {
required: true,
minlength: 6,
LowserCase: true,
Digit: true,
Special_char: true
}
},
messages: {
pwd: {
required: "password is required",
minlength: "Enter atleast 6 characters"
}
},
});
});
$.validator.addMethod("Uppercase", function (value, element) {
return this.optional(element) || /[A-Z]/.test(value);
}, "Enter atleast one Capital letter");
$.validator.addMethod("LowserCase", function (value, element) {
return this.optional(element) || /[a-z]/.test(value);
}, "Enter atleast one Small letter");
$.validator.addMethod("Digit", function (value, element) {
return this.optional(element) || /[0-9]/.test(value);
}, "Enter atleast one Number");
$.validator.addMethod("Special_char", function (value, element) {
return this.optional(element) || /[{}|~`"'[\]$&+,:;=?##|'<>.^*()%!-]/.test(value);
}, "Enter atleast one Special Character");
Thanks in advance.
Your code...
$('.btn-md').on('click', function () {
alert('test');
$('#formresetpwd').validate({
....
While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.
Based on your code, you click the button and the alert fires, then the .validate() method is called. Nothing else is supposed to happen.
The .validate() method is not for triggering validation; it's only used to initialize the plugin on your form. It does not belong inside of a click handler. The plugin already captures the click of the submit button and automatically triggers any necessary validation.
$(document).ready(function() {
$('#formresetpwd').validate({ // <- INITIALIZE plugin
rules: {
....
},
....
});
$.validator.addMethod( ....
});
Working DEMO: jsfiddle.net/9vgpLmt5/
you have to set input element class="pwd"
<input type="password" name="pwd" id="pwd" class="txt pwd"/>

Clear jquery.validate error messages on change/hide of disabled attributes

Trying to clear the error messages when the disabled fields are toggled on and off on my form using jquery.validate. Right now I have it working where on change or on click fields are showing and changing the prop from disabled. So it works for what I need which is hiding the fields that are not necessary and not validating them when they are in a disabled state. However, when I toggle these fields back to their disabled state ad hide them, the error messages are still showing until I click submit again. I tried adding the .valid() call to the toggleDisabled function and it does not make the messages disappear when they go back to a hidden/disabled state. Anyone see what can be added to make the messages disappear when the fields do?
Here is the working fiddle with what I have so far:
JS Fiddle
And I am using jquery.validate from :
jQuery.Validate
HTML:
<form id="myform">
<input type="text" name="field1" />
<br/>
<br />
<input type="text" id="toggleInput" name="toggleInputName" disabled style="display:none" />
<input type="button" id="toggleButton" value="Toggle Disabled" />
<div id="tickets">
<label for="group1">Number of Tickets: <span class="req">*</span></label>
<select class="group1_dropdown" id="group1" name="group1">
<option value="0">-- Please select --</option>
<option value="1">Member</option>
<option value="2">Member + 1 Guest</option>
<option value="3">Member + 2 Guests</option>
<option value="4">Member + 3 Guests</option>
</select>
</div>
<input type="text" id="payMethod" name="payMethodName" disabled style="display:none" />
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('#myform').validate({
onblur: true,
onkeyup: false,
ignore: ":disabled",
rules: {
field1: {
required: true,
minlength: 5
},
payMethodName: {
required: true,
minlength: 5
},
toggleInputName: {
required: true,
minlength: 5
}
},
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
});
//used for toggling/showing disabled fields - will display and make not disabled on same click event
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.prop('disabled')) {
$this.prop('disabled', false).show();
} else {
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
$(function () {
$('#toggleButton').click(function () {
$('#toggleInput').toggleDisabled();
});
});
$(function () {
$("#group1").change(function () {
var str = "";
str = parseInt($(this).val());
if(str == 2)
$("#payMethod").toggleDisabled();
else
$("#payMethod").toggleDisabled();
});
});
I have changed your plugin a little to do what you want.
Fiddle Demo
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this),
id = $this.attr('id'), //get the id of input
label = $this.next('label[for="' + id + '"]'); //find the next label which is added by jQuery Validator
if ($this.prop('disabled')) {
label.show(); //show the label
$this.prop('disabled', false).show();
} else {
label.hide();//hide the label
$this.prop('disabled', true).hide();
}
});
};
})(jQuery);
Update
Another way without changing your plugin
Fiddle Demo
$(document).ready(function () { //place your all DOM ready code in one DOM ready handler
var validator = $('#myform').validate({ //assign validate to a variable
//validator code here
});
$('#toggleButton').click(function () {
validator.resetForm();//reset Form validation
$('#toggleInput').toggleDisabled();
});
});

jQuery Validation checkbox custom value rule

Is it possible to check for a custom value (besides True / False) on a checkbox using the jQuery Validation plugin?
For example :
<input id="test" type="checkbox" name="test" value="something">
I cannot find a way to check for 'something' being the value. For specific reasons I cannot just use 'true' as the value.
Try this :
$('#test').attr('value');
Demo JSFiddle
You can use it inside custo validation method.
To declare custom rule :
$.validator.addMethod("myRule", function(value, element) {
var v = element.attr('value');
if(v === 'something') {
return true;
}
return true;
}, $.validator.format('my message') );
To set the custom rule on a field :
$('#form').validate({
rules : {
test : {
myRule : true
}
}
});
Use:
$("#test").val()
or if you want to get value in change event then:
demo : http://jsfiddle.net/qsDn5/16/
$("#test").change(function(){
alert(this.value);
});
You can add the rule using the addMethod which then returns a boolean based on the result of a test like so:
// Add Custom Method
$.validator.addMethod('someTest', function(value, element){
return 'something' === value;
}, $.validator.format('Custom Message'));
// Use Custom Method
$('#theForm').validate({
rules: {
checkBoxField: {
someTest: true
}
...
});
JSFiddle Demo.
I hope this helps!
Try Jquery Validation plugin,
<form id="myform">
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<input type="submit" />
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>
Code:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
custommethod: true
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
Update: http://jsfiddle.net/aJBK9/2/
Use the addMethod in jquery Validation,
$.validator.addMethod("custommethod", function(value, element) {
if (value==="something"){return true;}
return false;
}, "Value must be some thing");
Check this demo link http://jsfiddle.net/aJBK9/1/

How to validate a more than one element in form like Name, City, and State by one function in real time?

i want to make one common function in javascript for validation of my fields like name,city and state.
which can be also applicable for all three fields
1) Name
2) City
3) State
Here is the code of html
<form name="addcust" method="POST" action="insrtCustomer.php" id="form1">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" name="name" id="name"><label id="message"></label></td>
<td>City</td><td><input type="text" name="city" maxlength="25"></td>
</tr>
<tr>
<td>State</td><td><input type="text" name="state" maxlength="25"></td>
</tr>
</table>
I want to make one function which i can use it for real time validation and can be applicable for more than one form.
As all you guys know that all forms in website has different name. So how it can be used, Please give your ideas here to do this and you all knows this can be usefull for other guys aso. So please help
you can try this and customize accordingly | Demo
Just you have to pass the form (this) in validate function and it will check for all text boxes for empty, you can modify it according to your use
<form name="addcust" method="POST" action="insrtCustomer.php" id="form1" onsubmit="return validate(this)">
<table>
<tr>
<td>Customer Name</td>
<td><input type="text" name="name" id="name"><label id="message"></label></td>
<td>City</td><td><input type="text" name="city" maxlength="25"></td>
</tr>
<tr>
<td>State</td><td><input type="text" name="state" maxlength="25"></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
Javascript
function validate(dis)
{
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}
If you want to check for special characters
function validate(dis)
{
var filter = /^[A-Za-z0-9]+$/;
var ele = dis.getElementsByTagName("input");
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute("type") == "text")
{
if(ele[i].value == "")
{
alert(ele[i].getAttribute('name')+" is required feild");
ele[i].focus();
return false;
}
else if(!filter.test(ele[i].value))
{
alert(ele[i].getAttribute('name')+" requires letters and numbers only");
ele[i].focus();
return false;
}else;
}
// you can check for radio and checkboxes
//eg : if(ele[i].getAttribute("type") == "radio")
// {
// Your code here
// }
}
return true; // to prevent from form submission use false
}
You can try this example JQuery Validation
Include your jquery validation file in html page after jquery file
$('#yourFormId').validate({
rules:{
name: {
required: true
},
city: {
required:true
},
state: {
required:true
}
},
messages: {
name:{
required: 'required msg'
},
city:{
required: 'required msg'
}, state:{
required: 'required msg'
}
},
submitHandler: function(form){
}
});
hope this will work...

Categories

Resources