jQuery Validation validator.addMethod not being fired? - javascript

$("#attribute-save-form").validate({
debug: false,
rules: {
txtAttributeName: "*",
txtAttributeLabel: "*",
txtLength: {
NotEqualtoZero: true
}
},
messages: {
txtAttributeName: "*",
txtAttributeLabel: "*",
txtLength: {
NotEqualtoZero: "Please enter length not equal to zero"
}
},
errorElement: "span",
invalidHandler: function (form, validator) {
$(validator.errorList).each(function (index, element) {
element.message = "*";
});
////
},
errorPlacement: function (error, element) {
$(error).insertAfter(element);
}
});
$.validator.addMethod("NotEqualtoZero", function (value, element, param) {
return this.optional(element) || /[^0]/.test(value);
}, "Not Equal to zero.");
});
I don't know what mistake I'm making or what I'm missing but it is just displaying * error message and not the "not equal to zero". Please tell me what I'm doing wrong
Update: I want to check that text value of text box is not equal to 0
i have debugg it the problem is in element my element "txtLength" is not coming
invalidHandler: function (form, validator) {
$(validator.errorList).each(function (index, element) {
element.message = "*";
my function "NotEqualToZero" is basically not being called here , am i missing somethig like i have include this in start
<script src="~/Scripts/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.extend(jQuery.validator.messages, {
required: "*"
});
is there anything else i have to include

Your NotEqualtoZero rule is working perfectly fine and showing the "Please enter length not equal to zero" error in this simple demo. Just enter 0 into the text box, click enter, and the error message appears: http://jsfiddle.net/tr22y/
However NotEqualtoZero is optional unless you also specify the required rule. In other words, there will be no error messages if you leave it blank.
The rest of your rules, however, do not make any sense at all.
rules: {
txtAttributeName: "*", // <- "*" is nonsense here
txtAttributeLabel: "*", // <- "*" is nonsense here
txtLength: {
NotEqualtoZero: true
}
},
There is no such rule as *. You have to enter the name of a single valid rule or key:value pairs of multiple valid rules.
Even so, that mistake still does not break anything. I cannot see your HTML markup, nor can I know which rules you need, but with your present jQuery code, the NotEqualtoZero rule still works perfectly as designed...
DEMO: http://jsfiddle.net/tr22y/2/
EDIT: After cleaning up the code in your question, you can also see that you have an extra }); at the very end. Perhaps you forgot the $(document).ready(function() { line from the top? Maybe a cut & paste mistake when you posted the question?

The above code works fine , my mistake was that i was giving element ids instead of element names in rules and messages in validate method, that's why add method was not calling.

Related

Clean previous JQuery validation error message

I have two validations for the same field and I´m using jQuery Validator, I would like to know how to clean the previous error message generated.
My problem now is that If I have the error for empty field, never is removed if I have another error like value must be higher than 10. I still showing "field must not be empty" when the value is 7.
I google on that and all suggestion are resetForm of validation.
var validator = $("#myform").validate(
);
validator.resetForm();
But of course if I do that the error message wont be showed. I just need to clean the previous error from the DOM before check for news.
Anyone knows another approach directly interacting with the DOM?
I´m trying this without success.
if ($.validator.defaults.onfocusout) {
$(element).unbind(".validate-biggerThanOrigin").bind("blur.validate-biggerThanOrigin", function () {
$(element).valid();
});
}
We´re defining the validation like this.
$.validator.addMethod("biggerThanOrigin", function (value, element, param) {
return biggerThanOrigin(value, element, param, validationMessages.biggerThanOrigin, validationMessages.referenceForkEmpty);
});
$.validator.addMethod("lessThanOrigin", function (value, element, param) {
return lessThanOrigin(value, element, param, validationMessages.lessThanOrigin, validationMessages.referenceForkEmpty);
});
Regards.
You should provide separate validation messages for errors.
$("#myform").validate({
rules: {
name: {
"required": true,
"minlength": 10
},
messages: {
name: {
required: "Please specify your name",
minlength: "Your name must be atleast 10 characters long"
}
}
});
This should work in your case.
EDIT:
Here is a working FIDDLE.
As you asked another approach , so here is the solution.
FIDDLE:
$('input').on('keyup', function () {
if ($(this).val().length == 0)
$('label').text('Field must not be empty');
else if ($(this).val() <= 10)
$('label').text('Value must be greater than 10');
else
$('label').text('');
});
This is just an example. You can use the approach.
Thanks anyway !

Parsley.js issues, adding class to parent of form field

I've seen this question a few times, and from what I can gather, either of these two options should work. However I cannot get errorsContainer to work. My goal is to add the error and valid classes to the direct parent of the form field. Extra kudos if if you can tell me how to disable the appending of the errors list while still adding these validation classes.
var parsleyConfig = {
errorClass: 'error',
successClass: 'valid',
errors: {
errorsContainer: function(el) {
return el.$element.parent();
//return $(el).closest('.parent');
}
}
}
var parsleyConfig = {
errorClass: 'error',
successClass: 'valid',
errorsContainer: function(el) {
return el.$element.parent();
//return $(el).closest('.parent');
}
}
$('#registerForm').parsley(parsleyConfig);
In both cases, the class is added to the form field itself, not its parent. Result is the same with data-parsley-validate included or not in the form element. Also running the latest 2.0 thanks!!
You have to use the classHandler option instead of errorsContainer
var parsleyOptions = {
errorClass: 'error',
successClass: 'valid',
errorsMessagesDisabled: true,
classHandler: function(el) {
return el.$element.parent();
}
};
$formSelector.parsley(parsleyOptions);
errorsContainer return the $element where errors messages will be appended as described in annotated source defaults options.
errorsMessagesDisabled prevent Parsley from adding errors list.

jQuery validate input if element hasClass

I am using the jQuery validation plugin to validate a checkout form on an ecommerce site. The validation works great, however I only need to validate inputs that don't have the class no-validate
Can I use the depends method to do this check? For example, would something like this work:
checkoutForm.validate({
rules: {
firstname: {
required: {
depends: function(element) {
return element.not('.no-validate');
}
}
}
}
});
Or do I have to do something different to do this check? I thought about wrapping the entire rules array in a conditional like:
if(!$(checkoutForm + ' input').hasClass('no-validate') { rules { //rules here } }
but I would rather use the depends method if possible.
Any help/tips would be greatly appreciated!
"The validation works great, however I only need to validate inputs that don't have the class no-validate"
Use the ignore option to ignore those…
checkoutForm.validate({
ignore: '.no-validate',
rules: {
firstname: {
required: true
}
}
});
See: http://jqueryvalidation.org/validate/#ignore

TypeError for jquery validation script

I want to try some simple example with jquery validate plugin in mvc application.
I have a JS module with this method:
ValidateRestriction: function (element) {
var inputs = $('form').validator();
inputs.data("validator").checkValidity();
$(element).validate({
rules :{
field: {
number: true,
"min": "1",
"max": "Infinity"
},
ignore: ".ignore",
onkeyup: false
}
});
}
But in console I get an error:
TypeError: $(...).validator is not a function
var inputs => $('form').validator();
In firebug I see that all needed JS functions are loaded. Verified in console:
>>> $.fn.validate
function()
What's the problem with this?
Your code:
ValidateRestriction: function (element) {
var inputs = $('form').validator();
inputs.data("validator").checkValidity();
$(element).validate({
rules :{
field: {
number: true,
"min": "1",
"max": "Infinity"
},
ignore: ".ignore",
onkeyup: false
}
});
}
These are your issues...
1) No such things as validator() and checkValidity() in the jQuery Validate plugin.
2) You cannot attach .validate() to an input element, assuming that's what your element argument is supposed to be. The .validate() method only gets attached to the form.
3) Your onkeyup and ignore options are placed improperly. These are siblings of the rules option, not siblings of field.
4) I have never heard of setting a max rule to "Infinity". If you leave out a max rule, the max value can be unlimited, or infinite.
5) You do not need quotation marks around the method names, nor do you need quotes around a numerical value.
6) I added the required rule for demonstration. Remove it if you don't want to make the input mandatory.
$(document).ready(function () {
$('#myform').validate({
rules: {
field: {
required: true,
number: true,
min: 1
}
},
ignore: ".ignore",
onkeyup: false
});
});
Working DEMO: http://jsfiddle.net/baCBE/
validator() and checkValidity() are not part of the the jquery validate plugin. Remove the first two lines then try the simplest possible case to see if your setup is correct
$(function(){
$('form').validate();
})
put a class="required" on some elements in your form and test that this is working

jQuery validate - specify only errorPlacement

I'm having difficulty getting error placement to work. I have a series of forms on my page, each using the built-in validation classes—required, number, etc—but for some reason the error placement isn't working. At all.
The rest of the form validation works great, but I'm not getting my alert to show.
$(".bundle-forms-form-container form").validate({
errorPlacement: function(error, element) {
alert("X");
var customTarget = $(element).closest("form").find(".errorHere");
if (true || customTarget.length)
customTarget.html(error);
//else
error.insertAfter(element);
}
});
It looks like the problem is that jQuery validate loses its mind if you call validate on a result set with multiple forms. The solution is simple
$(".bundle-forms-form-container form").each(function(i, el){
$(el).validate({
errorPlacement: function(error, element) {
var customTarget = $(element).closest("form").find(".errorHere");
if (customTarget.length)
customTarget.empty().append(error);
else
error.insertAfter(element);
}
});
});

Categories

Resources