jQuery Validate function not working - javascript

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/

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.

Select method is not validated dynamically

I am using a select method in form and when I click on submit method without filing the form, various errors are shown which I have included in validate methods, like first name required, email required, etc.
So the problem is when I start entering the first name, the error disappears. But the same is not happening in case of select method. When I select certain options there, the error still remains saying, select at least one option. This error goes away when I click submit button. But I want this error to go away when I select at least one option, like in the case of first name when I start typing, the error goes away.
I have included my validation methods in $(document).ready(function()
Any help will be appreciated.
The following is the code snippet:
var newusercontainer = $('#newUsererrorcontainer');
var newuservalidator = $("#newUserForm").validate({
submitHandler: function(form) {
registerUser();
},
errorContainer: newusercontainer,
errorLabelContainer: $("ul", newusercontainer),
wrapper: 'li',
meta: "validate",
rules: {
newUserFirstName: {
required:true,
maxlength:50,
},
sector: {
required: true,
},
},
messages: {
newUserFirstName: {
required: "The First name field is required.",
maxlength: "Please enter with in 60 characters"
},
sector: {
required: "The Sector field is required.",
},
}
});

jquery validation submitbutton not working after corrected validation error

When using the jQuery validation plugin (http://docs.jquery.com/Plugins/Validation/validate):
I want the following behavior: Validate as soon as the user presses submit (instead of actually submitting I am using an ajax post request).
What happens though is the following: As soon as submit is pressed, validation runs, I get a validation error when applicable, then when I correct the mistake, and press submit the form gets re-validated, but when there are no validation errors, the ajax post is not made, only the form gets validated.
When there are no validation errors in first instance, the post is made instantly, like it should.
I have the following:
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
onkeyup: false,
onclick: false,
onsubmit: true,
rules: {
telNR: {
required: true,
digits: true,
minlength: 10
}
},
messages: {
telNR: {
required: "Fill in a valid telephone NR",
minlength: "A telephoneNR is 10 characters long",
digits: "Use only numerics"
}
},
submitHandler: function(form) {
var jqxhr = $.post("sendMail.php", { telNR: $("#telNR").val() },
function(data) {
alert("Done");
})
.error(function(jqXHR){
alert("Error");
});
}
});
})
</script>
You may be having some ghost validation errors. Try adding the following to your options to cleanup the errors on focus of the form:
focusCleanup: true

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.

How to exempt element to be validated?

I'm using the validation plugin for jquery:
http://docs.jquery.com/Plugins/Validation.
I want to know how would I exempt a field to be validated? Currently all fields inside the form are automatically checked.
I am not sure if this will help since the element that I want to exempt is not included (obviously :) )
$("#contactForm").validate({
rules: {
first_name:{required: true,charsonly:true,minlength: 1 },
last_name:{required:true,charsonly:true,minlength: 1 },
birthday:{required:true,min:1,max:31 },
birthmonth:"required",
birthyear:"required",
username: {required: true,minlength:1,maxlength:32,username:true,notChinese:true,noSpecial:true},
password1:{required:true,minlength: 5,maxlength: 10, alphaNum: true },
password2:{required:true,minlength: 5,maxlength: 10, alphaNum: true, equalTo: "#password1"},
currency:"required",
address:{required: true,noSpecial:true,minlength:2},
city:{required: true,noSpecial:true,minlength:2},
state:{noSpecial:true},
countrycode:"required",
zip:{required:true,zipTest:true},
email:{required:true,email: true},
confirmemail:{required: true,equalTo: "#email",email:true},
phone:{required: true,minlength:6,maxlength:20,phoneUS:true},
cellphone:{required: true,minlength:6,maxlength:20,phoneUS:true},
custom06:{acceptIM:true}
} });
Found it.
I used the ignore validation method.
Here's the code
$("#myform").validate({
ignore: ".ignore"
})
It depends on class attribute. See examples:
This field is required and email format: it cannot be empty
input class="required email"
This field is NOT required and email format: it can be empty
input class="email"
This field is NOT required and doesnt have format: it can be empty
input class=""
Are you using some sort of server side technology? The validation library needs to have rules set, and if you are doing this in strictly javaScript (jQuery) it is manual.
UPDATE: You can remove rules with the following: http://docs.jquery.com/Plugins/Validation/rules#.22remove.22rules
Place the following at the end of the body.
$("selector").rules("remove");
You could set your own messages:
$("#contactForm").validate({
rules: {
input1: required,
input2: required,
no-validation: required,
input4: required,
},
messages: {
no-validation: ''
}
});
Just put an empty string for the field you don´t want to show any message for..

Categories

Resources