vivin / regula

Regula: An annotation-based form-validation framework in Javascript
126 stars 24 forks source link

Implement asynchronous validation #7

Closed vivin closed 11 years ago

vivin commented 13 years ago

Implement asynchronous validation. This is especially useful for validation that requires AJAX calls. Currently, any custom constraint that uses an AJAX call must be synchronous.

troyji commented 13 years ago

Perhaps something like this?

regula.validate(options); //synchronous
regula.validateAsync(callback, options); //asynchronous

This should be pretty straight forward to implement.

regula.validateAsync = function(callback, options)
{
    var asyncFunc = function()
    {
        var results = regula.validate(options);
        callback(results);
    }

    setTimeout(asyncFunc, 0); 
}

Example:

regula.bind();

function checkValidation(results)
{
    if(results.length > 0) alert("Invalid!");
}

regula.validateAsync(checkValidation);
vivin commented 13 years ago

That would be the easiest way. The difficulty arises when there are multiple asynchronous validation-constraints and so some sort of queuing mechanism will be required. Either that or count the number of asynchronous constraints and then only call the callback once all asynchronous constraints have been run. Right now I'm trying to focus on finishing the tests. It's pretty hard with work and school :(

troyji commented 13 years ago

Hmm... If you want to allow individual constraints to be async, things get complicated.

One option is to design the validate method to be async-capable all the time - similar to the validateAsync method I proposed earlier - and do some magic like you described to track the constraint progress. However, that is overly complex for non-async usage, which is probably the majority of the usage scenarios.

The other option is to leave a lot of responsibility on the user. They have to somehow know which constraints are async, keep track of which elements are using them, and only use the async validate function for those elements.

The advantage to doing this is that you can have 'multi-threaded' calls to servers. I suspect that scenarios with multiple long running 'threads' that could benefit from this are extremely rare.

The other advantage is simply to keep from bogging down the UI, which my original simplistic approach also provides. The downfall to my approach is that the 'threads' happen one at a time in sequence. A potential advantage to this is that you can 'break' the chain if any of the constraints return a false. With a 'multi-threaded' approach, all constraints are performed, un-necessarily, if a constraint fails.

If we can come up with a good design, I might be able to have some time to put into it.

vivin commented 11 years ago

Asynchronous validation has been implemented.