jQuery validation fails when using .element(element) within custom method - javascript

I have a custom rule that should check some dependencies by validating the other inputs this one depends on. When I do stuff like that validation for all other inputs seems to be ignored.
This one is my custom validation rule:
jQuery.validator.addMethod("checkDependencies", function (value, element) {
var valid1 = jQuery('form#add-lottery-form').validate().element('#input-1');
var valid2 = jQuery('form#add-lottery-form').validate().element('#input-2');
if (valid1 && valid2) {
return true;
} else {
return false;
}
}, 'dependencie error');
I have created a jsfiddle to show my problem:
http://jsfiddle.net/AQcrW/
steps to reproduce:
type something in input4 (this input is the one with custom rule "checkDependencies") [line 1 in JavaScript-part]
errors on input1 and input2 are shown due to calls in JS line 2 and line 3
insert correct values to input1 and input2
click submit
!!recognize that input3 was not validated!!
rerun the fiddle
click submit
all fields are validated as expected
Is this my fault or is it a bug in jQuery validation?

After some debugging and overview the plugins code i have a solution for my problem. I extended the validator plugin to be able to call the internal .check(element) function. this function just returns true/false. Its not a perfect solution because it does some stuff twice on form submit but at least it works so far.. so here is the code I added:
no need for the code - read edit!
jQuery.extend(jQuery.validator.prototype, {
check: function (element)
{
return this.check(element);
}
});
and here is the working fidde:
http://jsfiddle.net/HrPRL/
to follow my thoughts and maybe check out upcoming discussion:
https://github.com/jzaefferer/jquery-validation/issues/579
Edit:
As i realized right now my pretty cool jQuery extend doesn't have any effect..
because the .check() method is part of the prototype object you can access it already. So the code above is not needed.
Edit 2:
this is what I ended up with. It's working but I think some stuff could be optimized.
any better ideas to do it?
http://jsfiddle.net/HrPRL/6/
i am done.. thats enough for my intention: http://jsfiddle.net/HrPRL/8/

Related

Custom Unobtrusive Validation Method Not Firing as Per Documentation

I've been attempting to implement a ASP.NET MVC custom validation method. Tutorials I've used such as codeproject explain that you add data-val-customname to the element. Then jQuery.validate.unobtrusive.js then uses the third segment of the attribute
data-val-<customname>
as the name of the rule, as shown below.
$.validator.addMethod('customname', function(value, element, param) {
//... return true or false
});
However I just can't get the customname method to fire. By playing around I have been able to get the below code to work, but according to all the sources I've read Unobtrusive validation should not work like this.
$.validator.addMethod('data-val-customname', function(value, element, param) {
//... return true or false
});
I've posted an example of both methods
jsfiddle example
Any help would be much appreciated
I've updated my question hopefully to make clearer.
I have finally found got there in the end, but still feels like too much hard work and therefore I've probably got something wrong. Initial I was scuppered by a bug in Chrome Canary 62 which refused to allow the adding of a custom method.
My next issue was having to load jQuery, jQuery.validate and jQuery.validate.unobtrusive in the markup and then isolate javascript implementation in a ES6 class. I didn't want to add my adaptors before $().ready() because of my class structure and loading of the app file independent of jQuery. So I had to force $.validator.unobtrusive.parse(document);.
Despite this I was still having issues and finally debugged the source code and found that an existing validator information that is attached to the form was not merging with the updated parsed rules, and essentially ignoring any new adaptors added.
My final work around and admit feels like I've done too much, was to destroy the initial validation information before my forced re-parse.
Here is the working jsfiddle demo
Here is some simplified code
onJQueryReady() {
let formValidator = $.data(document.querySelector('form'), "validator" );
formValidator.destroy();
$.validator.unobtrusive.adapters.add("telephone", [], function (options) {
options.rules['telephone'] = {};
options.messages['telephone'] = options.message;
});
$.validator.unobtrusive.parse(document);
$.validator.addMethod("telephone", this.handleValidateTelephoneNumber);
}

Validate function works on ValidationTextBox but not on FilteringSelect. Why?

I'm having a rather strange behaviour and don't know if it's because something I'm not doing right.
I trying to customize a Dojo FilteringSelect in my application to show invalid messages at my will. Looking at the API, I found a way to do it. This way works fine for ValidationTextBox.
Code to switch validation state:
var originalValidator = textBox.validator;
textBox.validator = function() {return false;}
textBox.validate();
textBox.validator = originalValidator;
Here's a fiddle so you can take a look:
http://jsfiddle.net/phusick/HGBnq/
If I change the ValidationTextBox to a FilteringSelect, it should work the same. But for some reason, it doesn't!
Here's the fiddle:
http://jsfiddle.net/nachoargentina/HGBnq/421/
Any suggestions are greatly appreciated!
dijit/form/FilteringSelect does indeed inherit from dijit/form/ValidationTextBox, but it overrides isValid (source). isValid is what calls the validator function in ValidationTexBox.
You could compose your own FilteringSelect that uses the same method that ValidationTextBox uses for isValid, or whatever you wanted or needed to use.

Jquery .validate require_from_group

Whenever i use require_from_group it disables all other validations. Any ideas why?
Also is there a way to group "Telefon" and "Mobitel" and apply require_from_group to it?
$(document).ready(function(){
$("#fncMain").validate(
{
/*groups:{Call:"Telefon Mobitel"},*/
rules:{
Davcna:{required:true,exactlength:5, digits:true},
Idzav:{required:true,exactlength:5, digits:true},
Maticna:{required:true,exactlength:5, digits:true},
Telefon:{require_from_group: [1,".callme"]},
Mobitel:{require_from_group: [1,".callme"]}
},
messages:{
}}
);
});
All other fields not included here use simple "required" class. If i remove require_from_group rules applied to "Telefon" and "Mobitel" all other field validations work fine.
Thanks for help.
EDIT html : http://cl.ly/29391q0Q3G231T2I380m (too long to post it here)
#Tats_innit posted a custom require_from_group here: https://stackoverflow.com/posts/13127475
Turns out, this also fixes a logged github bug that was released with version 1.10.0 of require_from_group in additional-method-1.10.js for jquery.validation.
github issue:
require_from_group disables other rules
smileyanp#github quoted this post in his solution where he reused #Tats_innit's function and created a test that showed it works correctly and doesn't disable validation on other rules defined prior to the require_from_group.
This post is here as a time saver as this burned 3 hrs of googling for such a small detail..
FIX:
Just update additional-method-1.10.js or execute this code after additional-method-1.10.js has loaded (to overwrite the function).
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var fields = $(selector, element.form);
var filled_fields = fields.filter(function() {
// it's more clear to compare with empty string
return $(this).val() != "";
});
var empty_fields = fields.not(filled_fields);
// we will mark only first empty field as invalid
if (filled_fields.length < numberRequired && empty_fields[0] == element) {
return false;
}
return true;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
Edit: It actually looks like this fix has been incorporated into version 1.12.0 and you can find the CDN pointers for it here: http://jqueryvalidation.org/
And for reference:
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.js
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/additional-methods.js
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/additional-methods.min.js
I found this code below before I found the solution above, so my advice is to use the CDN links referenced above instead of pasting the code below into your JS file.
There is a better fix out on GitHub now (scroll to the very bottom), which I've copied here. This is not my work and the GitHub user sfreytag who wrote it, does not appear to be an SO contributor, I just wanted to get it into SO so other people who find this don't have to dig through threads on GitHub:
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var validator = this;
var selector = options[1];
var validOrNot = $(selector, element.form).filter(function() {
return validator.elementValue(this);
}).length >= options[0];
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
fields.valid();
$(element.form).valid();
fields.data('being_validated', false);
}
return validOrNot;
}, jQuery.format("Please fill at least {0} of these fields."));
I have done limited testing with this thus far, but it appears to be working as you'd expect, all validations occur (instead of blowing through any non "require_from_group" validations as before), so I'm happy with it so far. I just added it after the the validator declaration in the top of my JS code:
$.validator.setDefaults({
debug: true,
success: "valid"
});
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var validator = this;
var selector = options[1];
//continuation of code...

Identify which control my application is using

I got a method into my masterpage which populates a value to every label I pass:
function FillLabel(field, text)
{
$(field).html(text);
}
I'll need to make it adaptable to the situation that my field receive an html input and to put the text inside this input I need to use $(field).html(text);
I need to build an if to identify the type of the field and I have no idea how to do that. How can I do this?
You don't give enough details ! According to your code snippet, you seem to talk about JavaScript based on jQuery.
You can test the type of an element with the is() method and selectors :
var element=$(field);
if(element.is(":input")) element.val(text);
else element.html(text);
You can check the tag name:
var tag = $(field).attr('tagName');
edit — #Cédric Belin correctly suggests ".is()":
var isInput = $(field).is(':input');
Much more jQuery-like.
Or check to see if there's a "value" property:
if ('value' in $(field)[0]) { ... }
So, overall:
function FillLabel(field, text) {
var $field = $(field);
if ('value' in $field[0])
$field.val(text);
else
$field.html(text);
}
You might consider using ".text()" instead of ".html()" but I don't know what your application needs are. You also might consider writing this as a jQuery plugin.

Prototype: call custom function after validation

I'm using prototype and needs to call my function after succesfull validation.
Part of the code:
var validator = new Validation(this.form);
this will validate the form, but I don't know how to call my function trackForm after the validation is correct and the form is submited.
Any help?
I would need more details to answer, at least will try then.
I assume you're using PrototypeJS - the library. This lib does not support validation by default so you're probably using another library for that.
If you're using Dexagogo's validation (http://tetlaw.id.au/view/javascript/really-easy-field-validation) you will need to use onFormValidate callback.
I never used it, but presume you basically setup Validation like normally, with addition of that extra attribute. Like this:
var validator = new Validator(this.form, {onFormValidate: trackForm});
var trackForm = function (validationPassed, form) {
if (validationPassed) {
form.reset();
}
}
Ofc you don't need to create trackForm, but written as you mentioned about it.
Hope this somewhat helps.
I appreciate that the original question didn't mention the platform, but I found this question after Googling extensively for a solution on the Magento platform.
For those using Prototype through Magento and Magento's VarienForm, there's a simple way to do with without using any other validation libraries.
The validator is attached to the form when its initialised, and the onFormValidate method is an option on the validator.
You can access is as below:
this.form.validator.options.onFormValidate = function(validationPassed, form) {};
See the below example which I have tested for my own means and found it works exactly as expected:
var contactForm = new VarienForm('contactForm', true);
contactForm.validator.options.onFormValidate = function(validationPassed, form) {
if(validationPassed){
alert("Validation Passed");
}
}

Categories

Resources