jQuery Validation checkbox custom value rule - javascript

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/

Related

Minimum collective value of several inputs with jquery validate

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>

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();
});
});

auto-submit form only if specific number of checkboxes had been checked

I am new to jQuery. I am wondering if there is a way to count the number of checkboxes that have been checked and then auto-submit the form once a specific number of checkboxes had been checked. Let's say the user checks 2 checkboxes, nothing happens. The user checks the 3rd checkbox and the form submits.
<input type="checkbox" onclick="this.form.submit();">
You could try this, using no inline javascript...
HTML
<form>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
jQuery
$('input[type="checkbox"]').on('click', function (event) {
var flag = $('input:checked').length > 2 ? true : false;
if (flag) $('form').submit();
});
Fiddle
$('input[type="checkbox"]').on('change', function() {
if( $("input[type="checkbox"]:checked").length >=3) {
$('form').submit();
}
});
JQuery function:
function SubmitIfReady() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
}
HTML (form not shown):
<input type="checkbox" class="checkbox-class" onclick="SubmitIfReady();">
Or without the onclick:
JQuery function:
$(document).ready(function () {
$('.checkbox-class:checked').on('change', function() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
});
});
HTML (form not shown):
<input type="checkbox" class="checkbox-class">
Like this...
$(".counted-check").click(function(e){
var myForm = $(this).closest('form');
if(myForm.find(".counted-check").filter(":checked").length > 3){
myForm.submit();
}
});
http://jsfiddle.net/HQ5N9/

jQuery Validate: Validate that one field, or both fields of a pair are required

I have a form that I am trying to validate that has two fields:
<div class="entryForm">
<div class="formField">
<label for="fieldEmailAddress">Email address:</label>
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
</div>
<div class="formField">
<label for="fieldMobileNumber">Mobile number:</label>
<input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
</div>
</div>
Here's my jQuery Validation wireup:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
});
</script>
What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.
Any ideas?
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
else if(email.val() == '') {
alert('Email, please...');
}
else if(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
You simply need to include the additional-methods.js file and use the require_from_group method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.
// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup" to each input you need to group together...
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />
And finally, optionally use the groups option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.

Javascript validation not performing as exepected

I have a problem with my JS validation code. When I submit the form and there are errors, the form shouldn't go any further. But yet, the code doesn't stop, instead it carries on to the next line, which shows a successful message although there are still errors.
And I've clearly written that if, for example the field is empty, then return false...
Why does the code carry on to the next line, even though there's return false?
Press submit and you'll see what I mean.
JS:
(function(window, $) {
var Namespace = (function(Namespace) {
Namespace = {
// Main
run : function() {
this.validate.run('form');
},
// Validation
validate : {
// error message span
messageBox : '<span class="message" />',
// add any field here
fields : {
nameField : $('#contact-name'),
emailField : $('#contact-email'),
phoneField : $('#contact-phone')
},
// run validation
run : function(formName) {
$(formName).on('submit', $.proxy(this.validateField, this));
},
validateField : function() {
for (var field in this.fields) {
if (this.fields.hasOwnProperty(field)) {
this.checkField(this.fields[field]);
}
}
$('#general-message-section').text('Form successfully sent, thank you!');
return false;
},
checkField : function(field) {
var messageBox = $(this.messageBox);
field.closest('li').find('.message').remove();
if (field.hasClass('required')) {
if (!field.val()) {
messageBox.text('This field is empty!');
field.closest('li').append(messageBox);
return false;
}
}
if (this.fields.emailField.val()) {
this.fields.emailField.closest('li').find('.message').remove();
if (!this.fields.emailField.val().match(this.regEx.email)) {
messageBox.text('Only email format accepted!');
this.fields.emailField.closest('li').append(messageBox);
return false;
}
}
if (this.fields.phoneField.val()) {
this.fields.phoneField.closest('li').find('.message').remove();
if (!this.fields.phoneField.val().match(this.regEx.numbers)) {
messageBox.text('Only numbers are accepted!');
this.fields.phoneField.closest('li').append(messageBox);
return false;
}
}
},
regEx : {
email : /^([a-z0-9_\.-]+)#([\da-z\.-]+)\.([a-z\.]{2,6})$/,
numbers : /^[0-9]+$/
}
}
};
return Namespace;
}(Namespace || {}));
// make global
window.Namespace = Namespace;
}(window, jQuery));
// run it...
Namespace.run();
HTML:
<p id="general-message-section"></p>
<form id="contact-form" method="post" action="#">
<fieldset>
<ul>
<li>
<label for="contact-name">Contact name *:</label>
<input type="text" id="contact-name" tabindex="1" class="required" autofocus />
</li>
<li>
<label for="contact-email">Contact email address *:</label>
<input type="text" id="contact-email" tabindex="2" class="required" />
</li>
<li>
<label for="contact-phone">Contact phone number:</label>
<input type="text" id="contact-phone" tabindex="3" />
</li>
<li>
<input type="submit" id="submit-btn" tabindex="4" value="Submit" />
</li>
</ul>
</fieldset>
</form>
Many thanks
I guess you are missing a check in your validation logic. Your code:
validateField : function() {
for (var field in this.fields) {
if (this.fields.hasOwnProperty(field)) {
this.checkField(this.fields[field]);
}
}
$('#general-message-section').text('Form successfully sent, thank you!');
return false;
},
Does call checkField but doesn't check its result (which can be false). I guess you could have something like:
validateField : function() {
for (var field in this.fields) {
if (this.fields.hasOwnProperty(field)) {
if(!this.checkField(this.fields[field])) {
alert("There are errors!");
return false;
}
}
}
$('#general-message-section').text('Form successfully sent, thank you!');
return false;
},
And of course return true; in checkField if it's correct (at the end), or else it won't work either.
This will check all required fields and set valid to false if any checkField() return false but wont break the For loop, it will check if valid is false after the loop and break:
validateField : function() {
var valid = true;
for (var field in this.fields) {
if (this.fields.hasOwnProperty(field)) {
if(this.checkField(this.fields[field]) === false) valid = false;
}
}
if(!valid) return false;
$('#general-message-section').text('Form successfully sent, thank you!');
}
jsfiddle

Categories

Resources