最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论