jquery form.validate conditional required - javascript

I am trying to get a form to validate based on information that was submitted. Everything works fine if I make all fields required but my validation does not work as soon as I put in an if statement on the requirement.
Does not work:
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: $('#email').val() ? false : true
},
email: {
required: $('#mobile').val() ? false : true
}
},
});
Works fine:
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: true
},
email: {
required: true
}
},
});
Thanks for the help!

I generally use depends and works in my case
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: {depends: function(element) {
return jQuery("#email").val() == '' ? true : false;
}
}
},
email: {
required: {depends: function(element) {
return jQuery("#mobile").val() == '' ? true : false;
}
}
}
}
});

I think you missed the order of email and mobile
var form = $( "#send_request_sms" );
form.validate({
rules: {
first_name: {
required: true
} ,
last_name: {
required: true
},
mobile: {
required: $('#mobile').val() ? false : true
},
email: {
required: $('#email').val() ? false : true
}
},
});

I would recommend moving the conditional statement outside the validate object.
e.g.
var form = $("#send_request_sms");
var mobileRequired = $('#email').val() ? false : true;
var emailedRequired = $('#mobile').val() ? false : true;
form.validate({
rules: {
first_name: {
required: true
},
last_name: {
required: true
},
mobile: {
required: mobileRequired
},
email: {
required: emailRequired
}
}
});

Related

Validate.js ignoring other rules

I am using the validate.js plugin to validate my form. I have a method that validates at least one of the fields are filled in by the user. I used this Answer.
Here is my method:
$.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var validOrNot = $(selector, element.form).filter(function() {
return $(this).val();
}).length >= numberRequired;
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
fields.valid();
fields.data('being_validated', false);
}
return validOrNot;
}, "Please fill out at least 1 of these fields.");
The problem is that at least 1 field is filled works but the other required fields are being ignored.
Here is my form validation.
$("#clientaddressForm").validate({
submitHandler: function (form) {
// MY AJAX HERE
return false;
},
rules: {
addrcd: {
required: true
},
address1: {
required: true
},
areacode: {
required: true
},
zipcode: {
required: true
},
busname: {
required: function(element){
return $("#addrcd").val() != "R01" || $("#addrcd").val() != "R02" || $("#addrcd").val() != "R03";
}
},
tel: {
require_from_group: [1,".contactfillone"]
},
mobile: {
require_from_group: [1,".contactfillone"]
},
fax: {
require_from_group: [1,".contactfillone"]
},
},
messages: {
addrcd: {
required: "Please choose the address code",
},
address1: {
required: "Please enter the address",
},
areacode: {
required: "Please choose the area code",
},
zipcode: {
required: "Please choose the zip code",
},
busname: {
required: "Please enter the business/employment name",
}
},
errorPlacement: function(label, element) {
if(element.hasClass('web-select2') && element.next('.select2-container').length) {
label.addClass('mt-2 text-danger');
label.insertAfter(element.next('.select2-container'));
}
else{
label.addClass('mt-2 text-danger');
label.insertAfter(element);
}
},
highlight: function(element) {
$(element).parent().addClass('has-danger');
$(element).addClass('form-control-danger');
},
success: function(label,element) {
$(element).parent().removeClass('has-danger')
$(element).removeClass('form-control-danger')
label.remove();
}
});
}
What can I do to fix this?

errorPlacement can not be validate in first call but work fine in second click

using following function for validating but cant be work fine in first time but work fine in second time.
second function is used for validator and its not working fine when i first click the button but its work fine second time please help.
function saveValue(){
if (validateFormset().form()) { // validation perform
$('form#vendorActionForm').attr({methos: 'POST'});
$('form#vendorActionForm').attr({action: 'vendorAddressCreateUpdate.htm'});
$('form#vendorActionForm').submit();
}else{
$(".textMessgeClass").text("Please fill the highlighted field/s");
$(".textMessgeClass").addClass('errorClass');
$(".textMessgeClass").fadeIn("slow");
$(".textMessgeClass").delay(2000).fadeOut(2000);
}
}
function validateFormset(){
var validator = $("#vendorActionForm").validate({
rules: {
accountType: {
required:true
},
addressRank: {
required:true
},
street: {
required:true
},
city: {
required:true
},
state: {
required: true,
accept: "[a-zA-Z]+",
minlength: 2
},
region: {
required: true
},
zipCode: {
required: true,
rangelength: [3, 5]
},
contactName: {
required: true
},
mobile: {
required: false,
number: true,
minlength: 10
},
email: {
required: true,
email: true
},
email2: {
required: false,
email: true
},
email3: {
required: false,
email: true
}
},
errorPlacement: function(error, element) {
$(element).filter(':not(.valid)').addClass("addressErrorClass");
},
success: function(error) {
$("#vendorActionForm").find('.valid').removeClass("addressErrorClass");
}
});
alert('AAAA');
alert(validator);
return validator;
}

Trying to fire jquery validate on form submit using .submit

But it isn't firing when I hit submit. It submits but doesn't do anything. Any ideas? The alert doesn't even get called :(
The page I'm doing this on, is my Checkout page on:
http://rsatestamls.kaliocommerce.com
(Need a product in your cart to proceed to checkout)
My Javascript code is:
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
});
$("#CheckOut").submit(function (event) {
alert("Handler for .submit() called.");
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
FirstName: {
required: true
},
LastName: {
required: true
},
Email: {
required: true,
email: true
},
Phone: {
required: true,
digits: true
},
Address1: {
required: true
},
City: {
required: true
},
PostalCode: {
required: true,
digits: true
},
Country: {
required: true
},
State: {
required: true
},
pwd: {
required: true
},
pwd_confirm: {
required: true
},
FName_SHIP: {
required: true
},
LName_Ship: {
required: true
},
Phone_Ship: {
required: true,
digits: true
},
Address1_Ship: {
required: true
},
City_Ship: {
required: true
},
PostalCode_SHIP: {
required: true,
digits: true
},
COUNTRY_SHIP: {
required: true
},
State_SHIP: {
required: true
},
NameOnCard: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CreditCardType: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardNumber: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpMonth: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CardExpYear: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
CVC: {
required: {
depends: function (element) {
return $("#CCMethod").is(":checked");
}
}
},
customernumber: {
required: {
depends: function (element) {
return $("#OnAccount").is(":checked");
}
}
}
}
});
});
populateCartTotal();
</script>
Your submit handler isn't in your $(document).ready block, but should be. The handler is never getting attached.
In fact, you shouldn't use a submit handler at all, here. Just put your validate call in the ready block. See the demo here: http://jquery.bassistance.de/validate/demo/
<script>
$(document).ready(function () {
$("#Method input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$('input[type=checkbox][id=OnAccount]').prop('value', 'True')
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
} else {
$('input[type=checkbox][id=OnAccount]').val('No');
}
});
$("#CheckoutOptions input:checkbox").change(function () {
if (this.checked) {
var checkname = $(this).attr("name");
$("input:checkbox[name='" + checkname + "']").not(this).removeAttr("checked");
}
});
// move this stuff to here
jQuery.validator.setDefaults({
debug: false,
success: "valid"
});
$("#CheckOut").validate({
rules: {
// all those rules here
}
});
});
populateCartTotal();
As an addendum to Ed's answer, I would also recommend setting up your validation scheme outside of the submit() handler.

line up multiple objects having same data (reduce redundancy)

I am developing a web application and i have used jquery validation as :
$("#register").validate({
rules: {
emailID: {
required: true,
email: true
},
pass: {
required: true,
minlength: 6
},
user_email: {
required: true,
email: true
},
user_pass: {
required: true,
minlength: 6
}
}
everything is working but the problem is as object emailID and user_email both are having the same data also same for pass and user_pass, how can i line them in one without changing my name attribute in html, something like this :
$("#register").validate({
rules: {
emailID, user_email:
{
required: true,
email : true
}
}
i know this structure is not correct.
and as i am having lots of objects having same data, so it doesnt seems to be good doing the repetition
function RequiredRule( email, minlength ) {
this.email = email;
this.minlength = minlength;
this.required = true;
}
$("#register").validate({
rules: {
emailID: new RequiredRule(true),
pass: new RequiredRule(false, 6),
user_email: new RequiredRule(true),
user_pass: new RequiredRule(false, 6)
}
});
var one = {
required: true,
email: true
},
two = {
required: true,
minlength: 6
};
$("#register").validate({
rules: {
emailID: one,
pass: two,
user_email: one,
user_pass: two
}
});

jquery validation missing : after property id

I changed my validation function a bit, because i wanted to include messages, and it throws missing : after property id now on line 2 in this code
$("#order").validate({
$("#vardas").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#pavarde").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#adresas").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#telef").rules("add", {
required: true,
digits: true,
messages: {
required: "Reikalingas laukas",
digits: "Turi susidaryti iš skaičių"
}
});
$("#email").rules("add", {
required: true,
email: true,
messages: {
required: "Reikalingas laukas",
email: "Patikrinkite ar teisingai įvestas el. pašto adresas"
}
});
submitHandler: function(form) {
$(form).ajaxSubmit();
$("#aciu").show(1000);
$("#duomenysdiv").hide(500);
}
});
any idea what's going on?
You can only call .rules() after .validate() has run, and not within the object declaration (the reason for your current error). Adding rules based on ID should look like this:
$("#order").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
$("#aciu").show(1000);
$("#duomenysdiv").hide(500);
}
});
$("#vardas").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#pavarde").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#adresas").rules("add", {
required: true,
messages: {
required: "Reikalingas laukas"
}
});
$("#telef").rules("add", {
required: true,
digits: true,
messages: {
required: "Reikalingas laukas",
digits: "Turi susidaryti iš skaičių"
}
});
$("#email").rules("add", {
required: true,
email: true,
messages: {
required: "Reikalingas laukas",
email: "Patikrinkite ar teisingai įvestas el. pašto adresas"
}
});

Categories