JQuery form validations plugin regex (pattern method) problems - javascript

this is my first post ever on stack overflow!
I've been trying to use the jquery validator plugin to validate my register form on php without submitting it (i already have server-side validations). Well, i don't know much about js (for now) but i'm trying to use jquery validation from this plugin https://jqueryvalidation.org/
I'm also using the additional-methods.js (pattern included) which gives you more validation methods.
Let me explain my situation... I'm using regex on php to validate my html forms and it works like a charm. When i tried to use the same regex for jquery it'd throw and error (i already have some basic code js and it works).
I tried a lot of regex formats and nothing works, i don't know what i'm doing wrong. I also tried to escape the code and it doesn't throw errors but it still doesn't work.
I'm getting "invalid format" all the time and i can't seem to understand why is it not working.
All the regex formats i've found on the internet don't work, it's crazy, maybe you can help me.
This is the pattern i'm actually using to validate the nombre (name) input in php: /^\pL+(?>[ ']\pL+)*$/u
*Also I've copied the patterns method inside my local js and removed the additional-methods cdn from my .php but it's the same.
** Ignore the [A-Z] thingy, i've been trying a lot of things, none of them work :(
Here my local.js
$.validator.setDefaults({
errorClass: 'text-danger position-absolute ml-1',
highlight: function
(element) {
$(element)
.closest('.form-control')
.addClass('is-invalid');
},
unhighlight: function (element) {
$(element)
.closest('.form-control')
.removeClass('is-invalid');
},
errorPlacement: function (error, element) {
if (element.prop('type') === 'checkbox') {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("pattern", function (value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp("^(?:" + param + ")$");
}
return param.test(value);
}, "Invalid format.");
$("#reg_form").validate({
debug: true,
rules: {
nombre: {
required: true,
pattern: [A-Z]
},
apellido: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true,
},
password: {
required: true,
strongPassword: true
},
cpassword: {
required: true,
equalTo: '#password'
}
},
messages: {
nombre: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
apellido: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
email: {
required: 'Please enter an email address.',
email: 'Por favor ingresa un email <em>válido</em>.',
},
password: {
required: true
}
}
});

You may have a minor oversight, change your pattern implementation to -
nombre: {
required: true,
pattern: "^[A-z\s]+$"
},
your pattern needs to be a string for it to be implemented. Secondly while \pL does work well to get any letter form any language, but not all programming languages have it implemented. (look here for what you can do in java script) You are better off just adding in the few extra letters you expect to encounter in the regex.

Related

Skip validation of model attribute using Backbone.Validation

I have a view that is rendered dynamically. It may have some inputs or may not have.
After a user fills everything and tries to send data I call this.model.isValid(true) ( or this.model.isValid() ) and it returns false even if the data from inputs is valid.
I think the cause is Backbone Validation tries to validate attributes of inputs we did not render.
Is there any solution to skip model attributes if we have no sticked elements of a view?
UPDATE:
My model is similar to this:
MyApp.module("RecordModel", function (RecordModel, MyApp, Backbone) {
RecordModel.recordModel = Backbone.Model.extend({
validation: {
inn: {
pattern: 'inn',
msg: MyApp.messages.inn
},
bik: {
pattern: 'bik',
msg: MyApp.messages.bik
},
uin: {
pattern: 'uin',
msg: MyApp.messages.uin
},
sum: {
pattern: 'sum',
msg: MyApp.messages.sum
}
}
});
});
Bindings:
bindings: {
'#uin': {
observe: 'uin',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#bik': {
observe: 'bik',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
},
'#inn': {
observe: 'inn',
setOptions: {
validate: true
},
events: ParkingMate.Validation.events.inputEvents
},
'#sum': {
observe: 'sum',
setOptions: {
validate: true
},
events: MyApp.Validation.events.inputEvents
}
}
So for some reason we din't render #sum input for instance. As we haven't it got in our DOM, it doesn't exists in RecordModel, but backbone still tries to validate it. Or if we have this input in our DOM, everything works fine.
How can I allow empty values but still validate if the user enters something?
By default, if you configure a validator for an attribute, it is
considered required. However, if you want to allow empty values and
still validate when something is entered, add required: false in
addition to other validators.
validation: {
value: {
min: 1,
required: false
}
}
If you can't let empty values (like at creation), Backbone.validation overrides isValid adding features to the default behavior. What's interesting is the array parameter we can pass:
// Check if name and age are valid
var isValid = model.isValid(['name', 'age']);
With this, we can then validate only the fields that exist within the model at the moment:
model.isValid(_.keys(model.attributes));

jQuery Validate function not working

This problem, i am sure is very trivial but i am not able to get past it.
My form is not getting validated using jquery validate.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
email: "required",
passwd: "required",
email:{
minlength: 10
}
},
messages: {
email: "Please enter your email",
passwd: "Please enter your passwd",
email:{
minlength: "Minlength has to be 10"
}
},
submitHandler: function(form) {
$("#pp").text("right");
form.submit();
}
});
})
No console errors. I have following
name, passwd are name, id of the fields i am trying to validate and loginForm is id of form. The problem is i don't see the error messages when i pass invalid input. Going through debug mode, i don't see the stack reaching inside validate function ever although an alert inside ready function before validate is called.
You did not show your HTML markup, so this answer assumes you correctly named your input elements.
In your code, you're specifying email twice...
rules: {
email: "required",
passwd: "required",
email:{ // <- duplicate
minlength: 10
}
},
If you need to specify multiple rules for one field, then specify the field once and list the rules inside...
rules: {
email: {
required: true,
minlength: 10
},
passwd: "required"
},
Your messages option has the same problem.
Working DEMO: http://jsfiddle.net/4937t/

Syntax error: missing : after property (jQuery validate)

I am building a set of jQuery validate rules to be used for a form prototype.
I am getting a JS error with my code. Chromes complains with the error
[14:30:27.722] SyntaxError: missing : after property id
at the location specified in the code comments.
here is the code:
$.validator.addMethod("regex", function(value, element, regexpr) {
return regexpr.test(value);
}, "Entree invalide");
$('#mainform').validate({
rules: {
form-nocivique: { //Chrome complains here
required: true,
digits: true
},
form-rue: "required",
form-province: "required",
form-codepostal: {
required: true,
regex: /([ABCEGHJKLMNPRSTVWXYZ]\d){3}/i
}
},
});
Any idea why?
Your property names (some of them) are invalid identifiers.
You can quote it to fix the problem:
rules: {
"form-nocivique": { //Chrome complains here
required: true,
digits: true
},
You can't use - in an identifier in JavaScript; it's a token (the "minus" operator).

jQuery required( dependency-expression ) is not working properly

I am using jquery validation plugin. When I was using required( dependency-expression ) i noticed that
required( dependency-expression ) are not working properly. as mentioned that i tried for
$("#flight_availability").validate({
rules: {
Trip: { required: true },
DepartDate: { required : "#OneTrip:checked" },
Origin: { required:"#OriginId:blank" }
},
});
In the above mentioned code the code DepartDate: { required : "#OneTrip:checked" }, works fine but Origin: { required:"#OriginId:blank" } does not work.
Whats wrong with the code? I used firebug. It did not show any errors. even used validation debug option too, but :(
As per OP's comments:
"even if OriginId is empty(blank), it validates it as true"
Yes, that is exactly how you programmed it.
Origin: {
required: "#OriginId:blank"
}
The above code is saying that the Origin field is only required when the #OriginId field is left blank. Using #OriginId:filled, this logic is saying that the Origin field must remain empty if the #OriginId is filled in. If that's not exactly correct, then you can use the :blank selector instead.
http://jsfiddle.net/xMAs5/
If you want the opposite behavior then use the :filled selector instead.
Origin: {
required: "#OriginId:filled"
}
http://jsfiddle.net/xMAs5/1/
Otherwise, here is a demo using a custom method called empty that works as per your comment: "So if OriginId is empty means Origin value (anything) is invalid."
$(document).ready(function () {
$.validator.addMethod('empty', function (value, element) {
return (value === '');
}, "This field must remain empty!");
$("#flight_availability").validate({
rules: {
Trip: {
required: true
},
DepartDate: {
required: "#OneTrip:checked"
},
Origin: {
empty: {
depends: function (element) {
return $("#OriginId").is(":blank")
}
}
}
}
});
});
DEMO: http://jsfiddle.net/Ab8bT/
It might be the jQuery puesdo selector try using :empty instead of :blank.

jQuery Validate with input arrays

The following code results in the following error:
SyntaxError: Unexpected token ).
Any ideas?
$("#signupForm").validate({
rules: {
'entry[first_name]': "required",
'answers[985575][answer]': "required",
'answers[985574][answer]': {
required: true,
phoneUS: true
},
'entry[email]': {
required: true,
email: true
}
}});
The phoneUS is not a standard, built-in rule. So unless you have defined it, it won't work. As explained in the documentation you need to define it. They provide the following method that you need to include in order to define the phoneUS rule:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
And here's a working live demo.

Categories

Resources