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?
Related
TLDR version: I have a custom jquery validation the returns the correct values but the rule is not getting enforced.
I have a custom validation rule that looks like this:
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
This validation calls a PHP API that checks if the email's domain name is live, hence correct. This API returns the correct values and the console.log() also reflects the correct values, which is the value I am returning as a boolean. All good so far...
I call this validation rule like this:
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
});
I also have some custom error messages (I think maybe irrelevant) like the following:
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
}, },
All my validations, including one other custom validation work flawlessly except this one. Here is all the code I am running in case someone wants to see the whole thing. Again, all validations work except the custom isDomainValid validation.
var validator = $('#checkout_form');
$.validator.addMethod("checkPoBox", function(value, element) {
let cleansedValue = $.trim(value.toLowerCase()).replace(/[^a-zA-Z]+/g, '');
let checked = $('#ship-box').prop('checked') ? true : false;
if (/pobox/i.test(cleansedValue) && checked && element.name == 'shipping_address') {
return false;
}
if (/pobox/i.test(cleansedValue) && !checked && element.name == 'billing_address') {
return false;
}
return true;
});
$.validator.addMethod("isDomainValid", function(value, element) {
var domain = value.split("#");
$.get('/api/validate-domain/' + domain[1], function(data, status) {
domain = JSON.parse(data);
console.log(domain['status'] === 'valid');
return (domain['status'] === 'valid');
});
});
validator.validate({
rules: {
email: {
required: true,
email: true,
isDomainValid: true,
},
billing_first_name: {
required: true
},
billing_last_name: {
required: true
},
billing_address: {
required: true,
checkPoBox: true
},
billing_city: {
required: true
},
billing_state: {
required: true
},
billing_zip: {
required: true,
minlength: 5,
maxlength: 5,
digits: true
},
billing_phone: {
required: true,
minlength: 10,
maxlength: 10,
digits: true
},
name_on_credit_card: {
required: true
},
credit_card_number: {
required: true,
creditcard: true
},
expiration_month: {
required: true
},
expiration_year: {
required: true
},
cvv: {
required: true,
minlength: 3,
maxlength: 4,
digits: true
},
shipping_first_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_last_name: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_address: {
required: function () {
return $('#ship-box').prop('checked');
},
checkPoBox: true
},
shipping_city: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_state: {
required: function () {
return $('#ship-box').prop('checked');
}
},
shipping_zip: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 5,
maxlength: 5,
digits: true
},
shipping_phone: {
required: function () {
return $('#ship-box').prop('checked');
},
minlength: 10,
maxlength: 10,
digits: true
}
},
messages: {
email: {
required: "The Email Address cannot be empty",
isDomainValid: "Please correct the Email Address after the # character",
email: "Invalid Email Address format",
},
billing_first_name: "First Name cannot be blank",
billing_last_name: "Last Name cannot be blank",
billing_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
billing_city: "Town/City cannot be blank",
billing_state: "Please select a State",
billing_zip: "Please enter a valid 5 digit Zip Code",
billing_phone: "Please enter a valid 10 digit Phone Number",
name_on_credit_card: "Name on Card cannot be blank",
credit_card_number: "Please enter a valid Credit Car Number",
expiration_month: "Please select an Expiration Month",
expiration_year: "Please select an Expiration Year",
cvv: "Please enter a valid 3 or 4 digit CVV",
shipping_first_name: "First Name cannot be blank",
shipping_last_name: "Last Name cannot be blank",
shipping_address: {
required: "Address cannot be blank",
checkPoBox: "Products cannot be shipped to a P.O. Box"
},
shipping_city: "City cannot be blank",
shipping_state: "Please select a State",
shipping_zip: "Please enter a valid 5 digit Zip Code",
shipping_phone: "Please enter a valid 10 digit Phone Number",
},
invalidHandler: function(event, validator) {
if(validator.numberOfInvalids() > 0) {
event.preventDefault();
$('button#place_order_btn').text("PLACE ORDER");
return false;
}
},
submitHandler: function (validator) {
validator.submit();
}
});
Any help will be greatly appreciated.
I think you're running into a problem where the return value for the success callback function is lost in the $.get method. In my experience I've had to trigger errors manually as part of the callback when checking against the server in a similar way.
Alternatively, I was digging around and found some jQuery Validation documentation that seems like it would make what you are trying to do a little easier: https://jqueryvalidation.org/remote-method/
Try updating the rules.email properties, replacing isDomainValid:
rules: {
email: {
required: true,
email: true,
remote: {
url: function() {
var value = $("[name='email']").val();
var domain = value.split("#");
return "/api/validate-domain/" + domain[1];
},
}
},
You can remove the call to $.validator.addMethod that registers the "isDomainValid" method.
Also, don't forget to update isDomainValid elsewhere, replacing it with remote so the messages are correct.
messages: {
email: {
required: "The Email Address cannot be empty",
email: "Invalid Email Address format",
remote: "Please correct the Email Address after the # character",
},
Here I am using jQuery validation. It is working fine, after fill all form fields I want do Ajax call but I am not able to do that. I am getting error. How can I do?
jQuery(document).ready(function(){
jQuery("#SubmitForm").validate({
rules: {
"address": {
required: true
},
"username": {
required: true
},
"mobileNumber": {
required: true,
number: true,
minlength : 12
},
"userEmailid": {
required: true,
email: true
},
"message": {
required: true
}
},
messages: {
"address": {
required: "Please enter your Location."
},
"username": {
required: "Please enter your Fullname."
},
"mobileNumber": {
required: "Please enter your Mobile Number."
},
"userEmailid": {
required: "Please enter your Email.",
email: "Please enter valid Email."
},
"message": {
required: "Please enter Message."
}
},
/* jQuery.ajax({
type:'POST',
url :"php/submit_hitachiForm.php",
data: jQuery('form#SubmitForm').serialize(),
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "success"){
$("#success_message").show();
$("#success_message").fadeOut(4000);
}
},
error:function(exception){
alert('Exeption:'+exception);
}
}); */
});
});
Put all the validation:
$('#SubmitForm).validate({
// validation rules
});
and after that initialize the validation function like:
if($('#SubmitForm).valid())
{
// make ajax() call here
}
Try this in your code
submitHandler: function() {
/*ajax request*/
}
I am trying to create a validation plugin for web application which evaluates the form when only the form-id is passed to the plugin using javascript/jquery
This is the code i have written where i have used the name of each field to evaluate the input for the html page
$(document).ready(function () {
$('#formId').validate({
rules: {
'Name': {
required: true,
minlength: 3
},
'Email': {
required: true,
minlength: 5
},
'password': "required",
'Confirm_password': {
required : true,
equalTo: "#password"
},
'test': {
required: true
},
'Radio': { required: true },
'ddl': {
required: {
depends: function (element) {
if ('none' == $('#select_field').val()) {
$('#select_field').val('');
}
return true;
}
}
}
},
messages: {
'Name': {
required: "Enter the name",
minlength: "The name should be atleast of 3 characters "
},
'Email': {
required: "Enter the emailid",
minlength: "The emailid should be atleast of 5 characters"
},
'test': {
required: "Check atleast one box"
},
'Radio':
{
required:"Please select an option<br/>"
},
'ddl':
{
required: "Please select an option from the list"
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
});
Use the Jquery Validation plugin.
Read this
I'm at coding a multi step form and have a question:
Is it possible in JavaScript or jQuery to activate this validation script:
<script type="text/javascript">
$(function (){
// Validation
$("#sky-form").validate({
// Rules for form validation
rules: {
country: { required: true },
industry: { required: true },
logoname: { required: true },
sloganch: { required: true }
},
// Messages for form validation
messages: {
country: { required: 'Please enter your name' },
industry: { required: 'Please check one of the options' },
logoname: { required: 'Please enter your Logo name' },
sloganch: { required: 'Please check one of the options' }
},
// Do not change code below
errorPlacement: function(error, element){
error.insertAfter(element.parent());
}
});
});
</script>
Only when this button is clicked :
<button type="button1" class="button next action-button" id="button4">Next</button>
It would be nice if the id="button 4" determine this function.
You can try this
$('#button4').click(function() {
$("#sky-form").validate({
// Rules for form validation
rules: {
country: { required: true },
industry: { required: true },
logoname: { required: true },
sloganch: { required: true }
},
// Messages for form validation
messages: {
country: { required: 'Please enter your name', },
industry: { required: 'Please check one of the options', },
logoname: { required: 'Please enter your Logo name' },
sloganch: { required: 'Please check one of the options' }
},
// Do not change code below
errorPlacement: function(error, element){
error.insertAfter(element.parent());
}
});
});
.validate() - to initialize the plugin (with options) once on DOM ready.
.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.
The answer is :
$('#button4').click(function()
{
// Validation
$("#sky-form").validate({
// Rules for form validation
rules: {
country: { required: true },
industry: { required: true },
logoname: { required: true },
sloganch: { required: true }
},
// Messages for form validation
messages: {
country: { required: 'Please enter your name' },
industry: { required: 'Please check one of the options' },
logoname: { required: 'Please enter your Logo name' },
sloganch: { required: 'Please check one of the options' }
},
// Do not change code below
errorPlacement: function(error, element){
error.insertAfter(element.parent());
}
});
});
If button code
<button type="button1" class="button next action-button" id="button4">Next</button>
Special thanks go to Satpal who answered my question .
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.