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",
},
Related
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?
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 want to validate my form using validate.js and match the password. I wrote the following code:
$(document).ready(function () {
$("#signup-form").validate({
rules: {
"signup-username": {
required: true,
minlength: 2
},
"signup-firstname": {
required: true,
minlength: 2
},
"signup-lastname": {
required: true,
minlength: 2
},
"signup-email": {
required: true
},
"signup-password1": {
required: true,
minlength: 5
},
"signup-password2": {
equalTo: "#signup-password1"
}
},
messages: {
"signup-username": {
required: "Please, enter a user name",
minlength: "Minimum userlength should be 2"
},
"signup-firstname": {
required: "Please, enter your first name",
minlength: "Minimum firstname length should be 2"
},
"signup-lastname": {
required: "Please, enter your last name",
minlength: "Minimum lastname length should be 2"
},
"signup-email": {
required: "Please, enter a valid email"
},
"signup-password1": {
required: "Please, enter your password",
minlength: "Minimum password length should be 5"
},
"signup-password1":"Password doesn't match."
}
submitHandler: function (form)
{
alert("form is submitted successfully.");
}
});
});
I am new to js. Why is it not working. Sometimes I wonder where to put comma and where not. Please help me.
Try change:
"signup-password2": {
equalTo: "#signup-password2"
}
...
"signup-password1":"Password doesn't match."
to:
"signup-password2": {
required: true,
equalTo: "#signup-password1"
}
...
"signup-password2": {
required: "Please, enter your password again",
equalTo: "Password doesn't match."
}
Doc
jsfiddle- validate plugin is broken
another fiddle - works correct
not familiar at all with this library, but I think you mean to check whether signup-password2 is equal to signup-password1. So it should read like:
"signup-password2": {
equalTo: "#signup-password1"
}
Keep getting this error. I've checked for hidden characters, deleted and retyped lines, etc. to no avail. Any ideas where this hidden character might be? I'm using almost identical code in another file which is working perfectly. Thanks!
$('#register-manager').validate({
rules:{
company-company_name: {
required: true
},
user-first_name: {
required: true
},
user-last_name: {
required: true
},
user-email: {
required: true,
email: true
},
user-password1: {
required: true,
min: 8
},
user-password2: {
required: true
}
},
messages: {
company-company_name: {
required: "Please enter your company's name."
},
user-first_name: {
required: "Please enter your first name."
},
user-last_name: {
required: "Please enter your last name."
},
user-email: {
required: "Please enter your email.",
email: "Please enter a valid email."
},
user-password1: {
required: "Please enter your password.",
min: "Please enter at least 8 characters."
},
user-password2: {
required: "Please verify your password."
}
},
submitHandler: function (form) {
form.submit();
}
});
There are no hidden characters (as far as I can tell). The problem is right there in the error message:
Unexpected token -
Identifiers in JS cannot contain - characters, try wrapping them in quotes like this:
$('#register-manager').validate({
rules:{
"company-company_name": {
required: true
},
"user-first_name": {
required: true
},
...