jQuery validate input if element hasClass - javascript

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

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 !

jQuery Validation validator.addMethod not being fired?

$("#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.

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.

Knockout Validation and Qtip

I currently use Jquery Validation and Qtip together to deal with the actual validation and displaying of information to the screen using the nice tooltip style notifications upon validation errors using the errorPlacement component of the validation options.
Currently each viewModel has its own custom method for setting up and kicking off the validation and callbacks, however I was trying to look at a nicer way of doing this, be it adding a custom binding to setup my validation rules via the data-bindings or an alternative way, but still yielding the same results (i.e the errorPlacement is triggered when a validation error occurs and tells Qtip to display the error for the given element).
Now before I started making one myself I just checked online and found Knockout Validation, which I initially thought was a great idea, I could apply my validation logic directly to the data within my viewModel and then just find some sort of callback to get Qtip to kick in, however it seems there is no callback that I can find documented. The library seems to do everything I want for the validation side of things, just not for the displaying side of things. I looked through the source code and examples but couldn't see anything other than ko.validation.group(viewModel) which would give me an observable containing the errors, but I am not sure if I could use this the same way as I was expecting.
Here is an example of how my current validation happens:
/*globals $ ko */
function SomeViewModel() {
this.SetupValidation = function () {
var formValidationOptions = {
submitHandler: self.DoSomethingWhenValid,
success: $.noop,
errorPlacement: function (error, element) {
if (!error.is(':empty'))
{ qtip.DoSomethingToDisplayValidationErrorForElement(element, error); }
else
{ qtip.DoSomethingToHideValidationErrorForElement(element); }
}
};
$(someForm).validate(formValidationOptions);
this.SetupValidationRules();
};
this.SetupValidationRules = function() {
$(someFormElement1).rules("add", { required: true, minlength: 6, maxlength: 20, alphaNumeric: true });
$(someFormElement2).rules("add", { required: true, minlength: 6, maxlength: 20 });
$(someFormElement3).rules("add", { required: true, email: true, });
};
}
I currently am sure I can remove the need for the validation rules method by adding a custom binding so I can set the validation in the data-bind, however if possible I would like to use the same sort of callback approach with the existing Knockout-Validation binding.
I haven't used Knockout-Validation specifically but I have written something similar in the past. A quick glance at the source shows that each extended observable gets a sub-observable isValid. This could be used to hide show messages in your markup using conventional knockout visible bindings.
To get QTip to work a custom binding could subscribe to this isValid property and perform the necessary initialization to show/hide QTip when triggered.
EDIT
Here is an example to get you started
http://jsfiddle.net/madcapnmckay/hfcj7/
HTML:
<!-- Note that you have to reference the "qtipValMessage" binding -->
<!-- using the "value" binding alone is not enough -->
<input data-bind="value: emailAddress, qtipValMessage : emailAddress" />
JS:
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
observable.isValid.subscribe(function(valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
});
}
}
};
I had been editing madcapnmckay's post, but the differences have become significant enough that I think a new answer is needed.
It is heavily based off of madcapnmckay's post, but it fixes a bug pointed out by MorganTiley. The original only works if the user has modified the observable. If they haven't then the code never gets fired. So, I've modified it so that it fires the tooltip code when it gets created, in addition to when it changes.
ko.bindingHandlers.qtipValMessage = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.qtip({
overwrite: true,
content: {
text: observable.error
}
});
} else {
$element.qtip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};
The one downside is that the tooltip will display on hover before knockout validation has been run (example, you have a "required" validation on a field, before you press submit a tooltip will display saying the field is required, but the field will not highlight in pink). Once you change the field however, the tooltip will disappear if the field is valid.
My app was not using qtip, but rather Twitter Bootstrap Tooltip, so here is the code for that as well.
ko.bindingHandlers.invalidTooltip = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var observable = valueAccessor(), $element = $(element);
if (observable.isValid) {
var updateTooltip = function (valid) {
if (!valid) {
$element.attr("data-original-title", observable.error);
$element.tooltip();
} else {
$element.tooltip("destroy");
}
}
updateTooltip();
observable.isValid.subscribe(updateTooltip);
}
}
};

improve my jquery validation plugin code

Just hoping soemone can help me to write better code than I can come up with on my own.
I am using the jquery validation plugin. I have some fields that are mandatory ONLY if certain options are chosen.
The below code works fine. But the thing is, is that that my list of 'OR's is much longer than I've put here. and it needs to be applied not just to 'directorsName' but a whole long list of inputs, selects etc.
My question is.. how can I wrap up the code contained inside the RETURN?
(so I dont have to keep repeating my 'OR's. I'm guessign I need a function but I'm unsure of the syntax)
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return ( $('#account_for').val() == "Joint" || $('#directors_number').val() == "2" || $('#directors_number').val() == "3" );
}
}
}
});
Thanks in advance
Here's a code snippet for a custom validator. You can apply this same syntax to your own custom validation needs.
$.validator.addMethod("noanon", function(value) {
return value.toLowerCase().indexOf("anonymous") != 0;
}, 'Do not hide behind the cover of anonymity')
You can then use it just like any of the built-in validation rules like:
name: {
required: true,
minlength: 2,
noanon: true
},
If you have not already read it, I suggest reading the 3-part blog that this code comes from over at coldFusion Jedi.
You can do this, which is supported cross browser using $.inArray():
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return $('#account_for').val() == "Joint" ||
$.inArray($('#directors_number').val(), ['2','3']);
}
}
}
});
list = ['1', '2', '3', '...'];
return $('#account_for').val() == "Joint" || list.indexOf($('#directors_number').val()) != -1;

Categories

Resources