guillaumepotier / Parsley.js

Validate your forms, frontend, without writing a single line of javascript
http://parsleyjs.org
MIT License
9.05k stars 1.32k forks source link

does isValid() ever return true with remote validations? #1333

Closed sdhull closed 4 years ago

sdhull commented 4 years ago

What kind of issue is this? (put 'x' between the square brackets)

The docs state

returns true if the promise is already fulfilled

This (to me) seems to indicate that if I call isValid() then the promise resolves, then call isValid() again, that it should return true. However what I've found is that it always returns null if any validations return a promise, and always kicks off that promise again.

If I'm reading this wrong, I think the docs could probably be clarified. On the other hand, if then intention is to memoize the result of validation with given inputs, it would seem this does not work. I have added simple isValid() assertions in the test that exercises whenValidate() to drive this out.

    expect(promise.state()).to.eql('pending');
    expect(form.isValid()).to.be.null
    deferred.reject();
    expect(promise.state()).to.eql('rejected'); // this is now 'pending' again
    expect(form.isValid()).to.be(false)
marcandre commented 4 years ago

tldnr: If you use async validator, you definitely should use whenValid instead of isValid...

Answer is: yes if a custom validator responds with an already fullfilled promise. If we ever remote jQuer as a dependency this would probably not be possible though, so maybe it would be best to specify to not rely on this in the doc?

The remote validator is a complicated case. There is a cache for remote requests (although it is cleared before submit, see #1181), but we call then on it. IIRC, depending on the version of jQuery you'll get a fullfilled promise, or a promise that will resolve next tick (to be compatible with the official promise spec). In short, I think it depends on your jQuery version.

In any case, you probably want to call whenValid instead of isValid and use promises.

sdhull commented 4 years ago

Aha thanks. I didn't grok that custom validators should implement their own cache. The docs talk about "the promise" a lot but I thought it was implied that parsley was building & maintaining that cache. Perhaps I was confused because of the cache for remote.

marcandre commented 4 years ago

Right, there are two different things: custom validators may return a promise (which may be dependent on an ajax call / UI to the user / whatever strikes your fancy), while the builtin remote validator will use a cache.

I'll close this, but PR for documentation always welcome.