Very simple example when I use function inside 'required' that should run on actual form validation but it also does execute on load of the page.
The question is how to avoid it and make so it would call other function inside required only on actual validation.
$("form").validate({
rules : {
testinput: {
required: runFunction('hello world')
}
});
function runFunction(a){
console.log(a);
}
Very simple example when I use function inside 'required' that should run on actual form validation but it also does execute on load of the page.
The question is how to avoid it and make so it would call other function inside required only on actual validation.
$("form").validate({
rules : {
testinput: {
required: runFunction('hello world')
}
});
function runFunction(a){
console.log(a);
}
Share
Improve this question
edited Oct 22, 2013 at 14:03
Sparky
98.8k26 gold badges202 silver badges290 bronze badges
asked Oct 22, 2013 at 11:45
devjs11devjs11
1,9588 gold badges43 silver badges73 bronze badges
3 Answers
Reset to default 1You need to wrap your function call inside another function:
$("form").validate({
rules : {
testinput: {
required: function(el) {
runFunction('hello world')
}
}
});
});
The reason for this is because the value returned from runFunction
is being set as the value of the required
property on load. With the above code you are assigning a function to the required
property which will only be run when validating.
Call function in required callback
like,
$("form").validate({
rules : {
testinput: {
required: function(){ runFunction('hello world');
}
}
});
Read required-method
another way would be using some sort of partial application
see maybe: Partial Application - Eloquent Javascript
your code might then be something among this lines:
$("form").validate({
rules : {
testinput: {
required: partial(runFunction,'hello world')
}
});
Where partial(runFunction,'hello world')
creates a new function which is eqivalent to runFunction('hello world').
This a powerfull concept from functional programming, and JS can be extended to support such a thing.
EDIT: 1 might be a better explanation of partial application
http://www.drdobbs./open-source/currying-and-partial-functions-in-javasc/231001821