jQuery validation - syntax error - javascript

I have the following jQuery code.
$(document).ready(function() {
$("#testform").validate(function() {
rules: {
firstname: {
minlength: 3,
required: true // error is here?
},
surname: {
minlength: 2,
required: true
},
gender: {
notEqualTo: "select"
}
},
messages: {
firstname: {
required: "Zadejte své jméno",
minlength: "Jméno musí mít délku alespoň 3 znaky"
},
surname: {
required: "Zadejte své příjmení",
minlength: "Jméno musí mít délku alespoň 2 znaky"
},
gender: {
notEqualTo: "Zvolte pohlaví"
}
},
errorContainer: "#errors"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
My web console displays me, that on line 6 (rules.firstname.required) is some syntax error. I can't see it. I tried also to switch minlength and required but the error still stays on the same line.
Can somebody see it?

Solution
Your error is that you're passing a function into validate:
$("#testform").validate(function() { // <-- here you're passing a function
// ...
})
where validate expects an object instead:
$("#testform").validate({ // <-- but you should pass an object
// ...
});
The syntax error is a consequence of declaring object properties on a function expression.
$("#testform").validate(function() {
rules: { // <-- (*)
// ...
},
// ...
})
(*) You're trying to define a property on an object but are declaring a label statement within a function expression.
Syntax Error Explanation
Defining a property on a function expression is valid syntax, although that is not actually what is happening. All that means is that you're declaring a label statement which has a label and a body and just happens to be within a function expression:
var x = function() {
rules: {} // label statement with label 'rules' and a body block expression
}
console.log(x.rules); // undefined. Not really useful
Parse Tree for the code above.
Nesting these label statements is also valid:
var x = function() {
rules: { // label statement with label 'rules' and a body block expression
name: 'test' // label statement with label 'name' and a literal expression 'test'
}
}
console.log(x.rules); // undefined
Parse Tree for the code above
As a matter of fact, we can even define label statements on their own:
rules: {} // valid syntax for a labeled statement with a label "rules" and a body block expression
Parse Tree for the code above
The syntax error happens once you add a second label by wrongly assuming you are adding properties to an object.
More accurately, the problem is the , (Comma Operator), which expects an expression but we're giving it a labeled statement instead:
rules: {}, // label statement with label 'rules' and a body block expression
messages: {} // <-- syntax error: thing before the comma is not an expression
Not having the , would eliminate the error since we would just have two independent labeled statements:
rules: {} // label statement with label 'rules' and a body block expression
messages: {} // label statement with label 'messages' and a body block expression
That's why the error is on line 6, because that is right after the first ,.
Removing all the commas will remove your syntax error and leave you with a bunch of labeled statements:
$(document).ready(function(){
$("#testform").validate(function(){
rules: {
firstname: {
minlength: 3
required: true
}
surname: {
minlength: 2
required: true
}
gender: {
notEqualTo: "select"
}
}
messages: {
firstname: {
required: "Zadejte své jméno"
minlength: "Jméno musí mít délku alespoň 3 znaky"
}
surname: {
required: "Zadejte své příjmení"
minlength: "Jméno musí mít délku alespoň 2 znaky"
}
gender: {
notEqualTo: "Zvolte pohlaví"
}
}
errorContainer: "#errors"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
Of course, this would still leave a bug in your code because you're passing wrong arguments to validate but at least would run :)

Related

JQuery form validations plugin regex (pattern method) problems

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.

Jquery Validation Rule Depends Generates Uncaught TypeError

When I try to use jQuery validation rules depends as follows:
<script>
$('#sign-up-form form').validate({
rules: {
state: "required",
school: {
depends: function(element) {
return $("#id_school_id").val().length;
}
}
}
});
</script>
Each time the depends part of the rule runs I get
Uncaught TypeError: Cannot read property 'call' of undefined
The id that I'm checking is there (#id_school_id).
I'm using jquery.validation.js v 1.11.1
I misunderstood depends to be a rule method. You need to apply its value to a rule method. So, for example
$('#sign-up-form form').validate({
rules: {
state: "required",
school: {
required: {
depends: function(element) {
return $("#id_school_id").val().length;
}
}
}
},
messages: {
school: "Please choose a valid school name from the choices presented"
}
});
</script>
Whether the field 'school' is required depends on the field 'school_id' having a length.

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).

How to check whether a value already exists using AJAX in jQuery validator?

$.validator.addMethod("noanon", function(value) {
return ajaxFunction();
}, 'Username already exists.');
The addMethod function takes 3 arguments. A name, the logic to actually run, and lastly, the default message to use for failures.
name: {
required: true,
minlength: 2,
noanon: true
},
Now if I use the ajaxFunction, there sems to be some error which is appearing.
You can use remote method:
rules: {
name: {
remote : "script.php"
}
},
messages: {
name: {
remote : "Page with this name is exists"
}
}
In PHP you take $_GET['name'].
Additional information here

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