how to validate a form for checkbox - javascript

I am trying to validate my checkboxes to ensure that a user clicks at least one checkbox. I am getting checkbox Names from the database. Can anyone solve this please.
$(function(){
$("#userFrm").validate({
rules: {
Item1: {
required: true,
},
},
messages: {
Item1: "Check atleast one box",
}
});
}
<form class="form-horizontal" action="" method="post" name="groupFrm" id="groupFrm">
<div class="control-group">
<label class="control-label">
Access Permission
<span class="error">*</span>
</label>
<div class="controls">
<div class="text-group">
{section name=source loop=$source}
<input type="checkbox" name="option1[]" id="Item1" class="first" {if in_array($source[source].id,$permission_user,true)} checked="checked"{/if} value="{$source[source].id}" />
{$source[source].mod_name}
{/section}
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" name="edit_permission" id="edit_permission" value="Update" class="btn btn-success " onclick="validate()">
</div>
</form>

You have use custom validation code to validate check box.
Try this.
$.validator.addMethod('yourRuleName', function (val, elm, param) {
//Validation code Here
return valid;
}, 'Your error message here');
$('#userFrm').validate({
rules: {
item1: {
yourRuleName: true
}
}
});

This will return true if at least one was checked:
$("input[type=checkbox]:checked").length>0
Or, this will count only the checked checkboxes within that form of yours:
$("#groupFrm:checkbox:checked").length>0

Related

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

Validate fields using jquery

I'm creating a form that requires to enter some fields.
The basic required attribute won't work on me, so I would like to use jQuery.
Then when those fields were already filled, the submit button will be enabled.
here's my code:
$(function() {
$('#catalog_order').validate(
{
rules:{
schedule: {
required: true
}
},
messages:{
schedule: "Please indicate schedule",
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', 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.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" /> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<label for="schedule"> Date: </label> <input type="date" id="schedule" name="schedule" value="M-D-YY"/> <!-- REQUIRED -->
<label for="figurine_select"> Figurine/s: </label> <!-- NOT REQUIRED, but still disable the CHECK IN NOW-->
<select name="figurine_sel" id="figurine_select" />
<option selected value=" ">--Figurines--</option>
<option value="angel">Angel</option>
<option value="teletubies">Teletubies</option>
</select>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled="disabled" />
</form>
Hope someone can help me out.
Thank you!!
This Fiddle Should work
Note that for every field you should specify all its option inside js object ( between brackets )
schedule: {
required: true
},
Below working snippet
jQuery.validator.addMethod("dateFormat", function(value, element) {
console.log(value,/^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value));
return /^(0?[1-9]|1[0-2])\/(0?[1-9]|1[0-9]|2[0-9]|3[01])\/\d{2}$/.test(value);
}, "Invalid Date !");
$(function() {
$('#checkin').validate(
{
rules:{
schedule: {
required:true,
dateFormat: true,
}
},
messages:{
required:"Required Field !"
}
});
$('#checkin input').on('keyup blur', function (e) { // fires on every keyup & blur
if ($('#checkin').valid()) {
$('#submit').attr('disabled', false);
}
else {
$('#submit').attr('disabled', 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.16.0/jquery.validate.js"></script>
<form role="form" id="checkin" name="checkin" method="post">
<label for="dedicatalog"> Dedication Text: </label> <input type="text" name="dedicatalog" id="dedicatalog" size="20" placeholder="Dedication" />
<label for="schedule"> Date: </label> <input id="schedule" name="schedule" placeholder="M-D-YY"/>
<input type="submit" id="submit" class="btn btn-default" value="Check In Now" disabled />
</form>
This is how I validate that.
return false is just the same us disabling it
<form role="form" id="checkin" name="checkin" method="post">
<input id="dedicatalog"/>
<input id="date" type="date"/>
</form>
<script>
$('#checkin').on('submit', function() {
var dedicatalog = $.trim($('#dedicatalog').val());
var date = $.trim($('#date').val());
if(dedicatalog == '' || date == '') {
return false;
}
});
</script>
You can use the invalidHandler parameter to check for any invalid fields:
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$('#button').hide();
} else {
$('#button').show();
}
}

JQuery validate disable button until all fields are active, but it should not show error on every key press

Here is my Fiddle
Here is the html
<form action='includes/pgd_cc.php' METHOD='POST' id="ccSelectForm">
<div class="control-group">
<label class="control-label" for="inputEmail"><strong>Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmail" placeholder="jane.smith#email.com" id="inputEmail" />
</div>
<label class="control-label" for="inputEmailConfirm"><strong>Confirm Email Address</strong>
</label>
<div class="controls">
<input type="text" name="inputEmailConfirm" placeholder="jane.smith#email.com" id="inputEmailConfirm" />
</div>
</div>
<button type="submit" id="emailSubmit" disabled="disabled" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Click me to buy">Credit Card Checkout ยป</button>
Here is the script
$(document).ready(function () {
$('#ccSelectForm').validate({
rules: {
inputEmail: {
required: true,
email: true
},
inputEmailConfirm: {
equalTo: '#inputEmail'
}
}
});
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
});
As i am doing
$('#ccSelectForm input').on('keyup blur', function () {
if ($('#ccSelectForm').valid()) {
$('button.btn').prop('disabled', false);
} else {
$('button.btn').prop('disabled', 'disabled');
}
});
My Form is always getting validated and showing errors.
I don't want to show the errors in the form while the user type a single word itself.
I want to show errors only after going to next field and it should only validate the current field is typed.
How can i alter this code to achieve this..
It is better to bind it to the submit. So that, it validates everything only once, and not every time for every input, when the keyup is fired. Try this:
$('#emailSubmit').on('click', function () {
return $('#ccSelectForm').valid();
});
Fiddle: http://output.jsbin.com/valiwetese

jQuery Validate forms by sections

i am trying to use jQuery validate to validate a big form that i have cut in 3 different sections.
personal information
job information
additional information
is there a way for me to validate the content every time the user hits continue? and then when they get to the last section they can submit the ENTIRE form?
form
<form method="post" name="form" id="form" class="form">
<div class="section_one form-wrapper-top-margin active">
<div class="columns-2 float-left">
<input name="name" id="name" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="email" id="email" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_1"/>
</div>
</div>
<div class="section_two form-wrapper-top-margin">
<div class="columns-1 margin-0">
<input name="address" id="address" type="text" class="" value=""/>
</div>
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_2"/>
</div>
</div>
<div class="section_there form-wrapper-top-margin">
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="submit" type="submit" id="submitbtn" value="Send your message"/>
</div>
</div>
</div>
</div>
</form>
i dont put the jQuery code here because i dont know where to start. i know jQuery validate, validates an entire form, but i never seen it done by sections with out splitting it into 3 different forms.
Thanks for the help...
You can do like this also:-
$(".section_two").click(function(){
//Your code for validation of section one.
});
$(".section_three").click(function(){
//Your code for validation of section one and section two.
});
$("#submitbtn").click(function(){
//Your code for validation of section three.
});
Let me know if this helps.
I found the answer here:
jQuery button validate part of a form at a time
this is the code i used
var validator = $('#form').validate({
ignore: 'input.continue,input#submitbtn',
rules: {
name: {
required: true
},
email: {
required : true
},
date: {
required: true
},
},
messages: {
name: "Enter your name",
email: {
require: "Please enter a valid email address",
email: "Enter a valid email"
},
},
errorPlacement: function(error, element) { },
});
$('#continue1').on('click', function(){
var tab = $(".section_one.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-1080px'});
}
});
$('#continue2').on('click', function(){
var tab = $(".section_two.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-2160px'});
}
});
thanks for everyone's advise...

Simple jquery validation - custom position error message placement

I am using jquery validate plugin to validate number in a form , how can i place the returned error message under the input button , i am unable to achieve,
Here is my image with the issue and what i need,pls check - http://i.imgur.com/Gt5aNxs.png
Please suggest me how to put the error message in a custom Div under the button instead of default underneath.
Here is my code:
<section id="contact" class="content">
<div class="container">
<h2>Contact Form Demo</h2>
<div class="row">
<div class="span12 contact-form">
<form action="mail.php" method="POST" class="form-horizontal contact-form" id="contact-form">
<!--<?php $formKey->outputKey(); ?> -->
<fieldset>
<div class="control-group">
<label class="control-label" for="inputPhone">Phone</label>
<div class="controls">
<input class="input-80" name="phone" type="text" id="inputPhone" placeholder="inc. country & area code">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" value="Send" class="btn" id="btn-place">Send!</button>
</div>
<div >place here</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</section>
<!-- javascript -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script>
// contact form validation
$(document).ready(function(){
$('#contact-form').validate(
{
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
minlength: 11,
required: false,
number: true
},
subject: {
minlength: 3,
required: true
},
message: {
minlength: 20,
required: true
}
},
highlight: function(label) {
$(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
}
});
// contact form submission, clear fields, return message,script no shown here
</script>
All you need to do is specify the errorLabelContainer in your options and specify the div you want the errors to go into:
$('#contact-form').validate({
//all your other options here
errorLabelContainer: '#errors'
});
Then just make sure you specify that your place here div has the id errors like this:
<div id="errors"></div>
See a working example here: http://jsfiddle.net/ryleyb/aaEFQ/ (note that I also specified the wrapper option, which you'll probably want if there are multiple errors).
errorPlacement: function(error, element) {
if((element.attr('name') === 'color[]')){
error.appendTo("div#errors");
}
else if(element.attr('name') === 'font[]' ){
error.appendTo("#font-error");
}
else{
element.before(error);
}
}

Categories

Resources