javascript - jQuery Validate - how to run function inside "required" without executing it on load - Stack Over

Very simple example when I use function inside 'required' that should run on actual form vali

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
Add a ment  | 

3 Answers 3

Reset to default 1

You 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744730748a4590452.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信