using multiples addMethod jquery - javascript

I want to customize the validations of my form using the addMethod function with the jQuery validator, but when I tried to add more than one method the validator seems to look only at the first one.
Here is the code:
jQuery.validator.addMethod("name", function(value, element) {
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{2,30}$/.test(value);
}, "please enter a valid name");
jQuery.validator.addMethod("surname", function(value, element) {
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}\-?[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}$/.test(value);
}, "please enter a valid surname");
$("#contactform").validate({
rules: {
firstname:{
required: true,
name: true,
minlength: 2,
maxlength: 30
},
lastname:{
required: true,
surname: true,
minlength: 2,
maxlength: 30
}
}
});
The issue is that on the last name I want to be able to add an '-' in case of a combined surname, I tried the regEx and it works exactly as I want to, but even if I call the method 'surname' in the rules of the field, it seems to elaborate the method 'name' anyway!
Thanks in advance for your help, I really don't understand what I'm missing here..
https://jsfiddle.net/2zumkcyg/11/

The issue is with your method name. The prop name inside rules is already a predefined rule inside $.validator like minLength. If you change name to anything but that it will work.
JS
$(document).ready(function(){
$.validator.addMethod("named", function(value, element){
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{2,30}$/.test(value);
}, "Please enter a valid name.");
$.validator.addMethod("surname", function(value, element){
return this.optional(element) || /^[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}\-?[A-Za-zÀ-ÖØ-öø-ÿ]{1,30}$/.test(value);
}, "Please enter a valid surname.");
$("#contactform").validate({
rules: {
firstname: {
required: true,
named: true,
minlength: 2,
maxlength: 30
},
lastname:{
required: true,
surname: true,
minlength: 2,
maxlength: 30
}
}
});
});
DEMO

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

How should I make my jquery validator work?(I think it doesn't wait for remote rule)

I am implementing a form validator with jQuery. However, it never works. Instead of showing any message, it shows an error. How can I make the validator work?
As I searched for other questions asking for similar problems, I've found some suggestions. One was changing remote into synchronousRemote, and one was adding submitHandler into the validator. I've tried them all, but nothing changed.
This is my validator code:
$("#createMember-form").validate({
ignore: "",
rules: {
name: {
required: true,
pattern: /^[a-zA-Z ]$/,
maxlength: 45
},
id: {
required: true,
minlength: 6,
maxlength: 15,
pattern: /^[a-zA-Z0-9]$/,
remote: {
url: "/member/checkUnique",
data: document.getElementById("#idField").value,
dataFilter: function (data) {
return data;
}
}
},
password: {
required: true,
minlength: 6,
maxlength: 15,
pattern: /^(?=.*[a-z])[A-Za-z0-9\d=!\-#._*]+$/
}
},
messages: {
name: {
required: "This field is required.",
pattern: "Your name should be written in English.",
maxlength: "It can't be longer than 45 letters."
},
id: {
required: "This field is required.",
pattern: "Your ID should be written in Romaji and numbers.",
minlength: "It can't be shorter than 6 letters.",
maxlength: "It can't be longer than 15 letters.",
remote: "The user using " + $("#idField").val() + " already exists."
},
password: {
required: "This field is required.",
pattern: "Your ID should be written in Romaji and numbers.",
minlength: "It can't be shorter than 6 letters.",
maxlength: "It can't be longer than 15 letters."
}
},
submitHandler: function (form) {
form.submit()
}
});
Building database table, I'd set up the entry id to be unique, the entry name, id, and password to never be null. And before going inside the validator, the for is submitted, and the error with the database occurs.
I guess that the reason is that it doesn't wait for the remote rule to be checked. If it is right, what should I for the form to wait? If not, what is the problem?

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 maxlength?

I am using JQuery validation plugin. I want to specify maxlength for one of the fields.It can be specified as below.
rules: {
Message: {
required: false,
maxLength: 200
}
}
But instead of defining the rules externally, i want to specify the rules inside html input code
Similar to :
<input type="text" name="AssistanPhone" value="" class="required" />
In above example "required" is specified through class. Similarly how can i specifiy maxlength which can be recognized by jquery plugin and gives error message if length exceeds?
Thanks!
Not capital L its l
Ex:
$( "#myform" ).validate({
rules: {
field: {
required: true,
maxlength: 200
}
}
});
PLUGIN DEMO
As far as I can see you cannot specify the messages via attributes, but the maxlength can be specified as a attribute
<input type="text" name="AssistanPhone" value="" required maxlength="3" />
Demo: Fiddle
I updated the javascript code of the validator myself (so I'm stuck with my version 1.8.1 now instead of upgrading), but here's what I did (around line 767):
classRules: function(element) {
var rules = {};
var classes = $(element).attr('class');
classes && $.each(classes.split(' '), function() {
if (this in $.validator.classRuleSettings) {
$.extend(rules, $.validator.classRuleSettings[this]);
}
if (this.toLowerCase().lastIndexOf('maxlength-', 0) === 0) { // starts with
var x = parseInt(this.substring(10)); // take number after 'maxlength-'
$.extend(rules, {maxlength: x});
}
});
return rules;
},
I added the extra if-test for "maxlength-", so now I can add a class like "maxlength-10" to limit to 10. Of course I could also add minlength and so on.
$("#FormID").validate({
rules: {
PriorityDDL: {
required: true
},
Title: {
required: true
},
Text: {
required: true,
maxlength: 300
},
date: {
required: true
},
reportfile: {
required: true
}
},
messages: {
PriorityDDL: {
required: "Please select priority"
},
Title: {
required: "Please enter title"
},
Text: {
required: "Please enter message",
maxlength:"maxLength is 300 characters"
},
date: {
required: "Please select date"
},
reportfile: {
required: "Please select file"
}
}
});

Disable automatic input focus with jQuery validator

I'm using jQuery Validator and I'd like to be able to disable the default focus behavior.
I am including the field names as values directly in the input fields themselves (like what you see in the "search" input at the top right side of Stack Overflow). The problem here, is that when I submit the form and a field is flagged as invalid, it automatically focuses on the field, which removes the field value.
This could be confusing for a user, as they no long know the purpose of that specific field. Is there any way to disable this behavior?
I've included my code below, in case that helps:
$(document).ready(function(){
jQuery.validator.messages.required = "";
jQuery.validator.addMethod("notEqual", function(value, element, param) {
return this.optional(element) || value !== param;
}, "");
$("#quoteForm").validate({
rules: {
firstName: {
required: true,
notEqual: "First name"
},
email: {
required: function(element) {return $("#emailAdd").val() == '';},
notEqual: "Email",
email: false
},
phone: {
required: function(element) {return $("#phoneNum").val() == '';},
notEqual: "Phone",
phoneUS: false
}
}
});
});
I found the answer to this and just wanted to share it here:
I simply needed to use focusInvalid: false.
Use Jeremy's answer like this:
$("#contactForm form").validate({
focusInvalid: false,
rules: {
name: "required",
email: {
required: true,
email: true
},
message: "required"
},
messages: {
name: 'Fill in name',
email: 'Fill in email',
message: 'Fill in message'
},
submitHandler: function(form) {
return SubmitContactForm();
}
});

Categories