validating the form with same input field names? - javascript

I have below jquery code to validate the form.
function validateForm(){
$("input.field1").each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "Required"
}
} );
});
$("input.fieldTwo").each(function(){
$(this).rules("add", {
required: true,
maxlength: 12,
email: true
messages: {
required: "Enter email",
email: "Enter valid email",
maxlength: "Maximum 12 characters"
}
} );
});
$("input.field3").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12
messages: {
maxlength: "Maximum 12 characters"
}
} );
});
$("input.field4").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12
messages: {
maxlength: "Maximum 12 characters"
}
} );
});
$("input.field5").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12
messages: {
maxlength: "Maximum 12 characters"
}
} );
});
return $("#myForm").validate({
onfocusout: function(element) { jQuery(element).valid(); }
});
}
But it always gives script error saying SyntaxError: missing } after property list.
But i believe no where } is required.
Am i missing anything here?
Thanks!

You're missing a comma here:
$("input.field3").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12, // added a comma here
messages: {
maxlength: "Maximum 12 characters"
}
} );
});
You've actually missed a comma in every single area after the maxlength property. Probably a copy and paste error?

You are missing several commas. See code, and replicate throughout.
$("input.fieldTwo").each(function(){
$(this).rules("add", {
required: true,
maxlength: 12,
email: true //MISSING COMMA
messages: {
required: "Enter email",
email: "Enter valid email",
maxlength: "Maximum 12 characters"
}
} );
});
$("input.field3").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12 //MISSING COMMA
messages: {
maxlength: "Maximum 12 characters"
}
} );
});
$("input.field4").each(function(){
$(this).rules("add", {
required: false,
maxlength: 12 //MISSING COMMA
messages: {
maxlength: "Maximum 12 characters"
}
} );
});

Related

jQuery Validate not acting on custom validation value

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",
},

Jquery validate plugin change default message

How can I change the default require message in Jquery validation plugin. I have tried the following, but it still prints the default message:
$("#form1").validate({
ignore: [],
debug: false,
rules: {
firstName: {
required: true,
minlength: 2,
maxlength: 200
}
message: {
firstName:{
required: "Custom error message."
}
}
}
});
});
UPDATE
I change my message into messages
messages: {
firstName:"Custom error message."
}
$("#form1").validate({
ignore: [],
debug: false,
rules: {
firstName: {
required: true,
minlength: 2,
maxlength: 200
},
messages: {
firstName:{
required: "Firstname required",
minlength: "Min length is 2",
maxlength: "Max length is 200",
}
}
}
});

Unable to match password using equalTo property

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"
}

Uncaught SyntaxError: Unexpected token - Can't find invisible character

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
},
...

JQuery validation plugin gives error?

I am using JQuery validation plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.js"></script>
Jquery code:
function validateForm(){
$('[name^="attribute"]').each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "Mandatory field"
}
} );
});
$('[name^="valueAttribute"]').each(function(){
$(this).rules("add", {
required: true,
maxlength: 12,
email: true,
messages: {
required: "Enter email",
email: "Enter valid email",
maxlength: "Maximum 12 characters"
}
} );
});
return $("#myForm").validate({
onfocusout: function(element) { jQuery(element).valid(); }
});
}
But above script gives error as below.
TypeError: $.data(...) is undefined
am i doing anything wrong here? It works fine if i remove all for each and go with default messages.
Thanks!
you are not using $(document).ready();
try this
$(document).ready(function(){
// do script here
});
hope it will help
The only problem seems to be, you are adding the rules to the elements before the validator plugin is initialized for the form
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/additional-methods.js"></script>
then
jQuery(function ($) {
function validateForm(){
var validator = $("#myForm").validate({
onfocusout: function(element) { jQuery(element).valid(); }
});
$('[name^="attribute"]').each(function(){
$(this).rules("add", {
required: true,
messages: {
required: "Mandatory field"
}
} );
});
$('[name^="valueAttribute"]').each(function(){
$(this).rules("add", {
required: true,
maxlength: 12,
email: true,
messages: {
required: "Enter email",
email: "Enter valid email",
maxlength: "Maximum 12 characters"
}
} );
});
return validator;
}
});
Demo: Fiddle

Categories