Prototype: call custom function after validation - javascript

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");
}
}

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);
}

XPages Validation with CSJS function call from submit button

I have a form that has a javascript validation function built from its previous functioning web site (i.e. old domino form). I am in the process of converting that website to xpages. Is it possible to tie that function as a CSJS to the save and close button like it was in the past application?
I only ask as there are lots of conditional validation requirements that would all need to be recreated that are existing in this function. . Also the form has tab pannels, and partial refresh conditions that I would have to code around to avoid refreshes calling validation, etc.
I have a feeling I will have problems with some of the calls, example:
document=document1;
form1 = document.forms[0] ;
val_AlphaSuffix = form1.Suffix.value ;
var msg="";
form = document.forms[0] ;
val_Eff_Date = form.Eff_Date.value ;
if (val_Eff_Date== "") {
msg=msg+"Effective Date is missing.\n";
}
If anyone has a better way of passing the document instead of each item, I would love to see that, but if not I think this answer by Tim T. probably is the best answer I can see:
Expression Language (e.g. #{id:Hours20}) can only be interpreted within the context of a component attribute, such as the onChange event code for a field. Once you move the code into a separate library, the code is no longer an attribute of a component, it's code that can be referenced in component attributes.
As with any other good function, design all client-side JavaScript functions to accept anything that might be context-sensitive as a parameter. For example:
function updateHours(inputId, outputId) {
var hours20 = XSP.getElementById(inputId).value;
XSP.getElementById(outputId).value = hours20;
}
Then your onChange event can reference this function, but pass in only the context-sensitive information:
updateHours("#{id:Hours20}", "#{id:Hours10}");
This way you're keeping reusable business logic in script libraries, which is always a good thing, but nothing in those libraries is assuming anything about page structure or server-side variables.
shareeditflag
answered Jan 16 '14 at 0:17
Tim Tripcony
7,73611532
There are a few moving parts you want to look at...
If you want to perform an entire client side validation, don't tie it to a button, but use the form event onSubmit="validate(this)". This will call your function with the form as parameter and you don't need to worry if you got the right form. You could use class parameters on your fields to specify generic validation requirements e.g. class="mandatory max_50" etc.
However be aware: client side validation is only for the comfort of the user, since it can be bypassed easily. Unless you are on very slow connection, you might want to take advantage of XPages server side validators and the error control.
Update: use the XSP object to add the event: https://www.notessensei.com/blog/2010/07/meet-the-xsp-object.html

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.

How to remove the "name" param in for fields in ExtJS 4

I am integrating a payment provider into a ExtJS websites.
Basically, a form needs to be created and the form fields is send to the payment provider using Ajax.
The problem is that the payment provider does not allow that the form fields has a "name" param assigned to the "" tag. They do a manual check of the implementation and makes sure it is not there.
I assume it is a counter-mesasure for when the visitor has Ajax dissabled and the form gets submitted to my server instead, revealing the credit card. I know it does not make any sense with ExtJS, as it would not work without Javascript turned on, but non-the-less, that is the rule from the payment provider.
So, how can I force ExtJS to not put a "name" param in the form field? I have tried putting "name: ''" into the fields, but that gets ignored.
Do I use the template-system in ExtJS to solve this?
So Eric is perfectly right that it can be done much easier then modifying the whole template but non the less I would use a plugin for such a special case. I made a quick one:
Ext.define('Ext.form.field.plugin.NoNameAttribute', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.nonameattribute',
init: function(cmp) {
Ext.Function.interceptAfterCust(cmp, "getSubTplData", function(data){
delete data['name'];
return data;
});
}
});
Note the used method interceptAfterCust is a custom one of mine that modify the existing one by handing the result of the original to the intercepting one as argument. It is also using the given original object (which can be threaten as a scope) as scope for the original method. The easiest would be to add these method to Ext.Function
Ext.Function.interceptAfterCust = function(object, methodName, fn, scope) {
var method = object[methodName] || Ext.emptyFn;
return (object[methodName] = function() {
return fn.call(scope || this, method.apply(object, arguments));
});
}
Here is a working JSFiddle where the first field will not have a name attribute on the dom even if it exist in the component.
There's a surprisingly simple solution to this. I tested it with Ext.form.field.Text and Ext.form.field.ComboBox and it works well, but I don't know if it works for all form fields or if there are any negative side-effects. Use with caution.
Ext.define('Override.form.field.Base', {
override: 'Ext.form.field.Base',
getSubTplData: function(){
var data = this.callParent(arguments);
delete data.name;
return data;
}
});
Basically, it removes the auto-generated name from the render data before passing it along. The best part is that no private methods are involved so this should be a stable solution.
I prefer this in the field config options:
submitValue: false
Available since ExtJS 3.4

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

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/

Categories

Resources