fix(forms): Verify functions passed into async validators returns Observable or Promise (#14053)

This commit is contained in:
Toxicable 2017-01-22 21:37:22 +13:00 committed by Miško Hevery
parent ff290af38c
commit 94f84c5d7e
2 changed files with 15 additions and 0 deletions

View File

@ -419,6 +419,10 @@ export abstract class AbstractControl {
if (this.asyncValidator) {
this._status = PENDING;
const obs = toObservable(this.asyncValidator(this));
if (!(obs instanceof Observable)) {
throw new Error(
`expected the following validator to return Promise or Observable: ${this.asyncValidator}. If you are using FormBuilder; did you forget to brace your validators in an array?`);
}
this._asyncValidationSubscription =
obs.subscribe({next: (res: {[key: string]: any}) => this.setErrors(res, {emitEvent})});
}

View File

@ -40,6 +40,8 @@ export function main() {
function otherAsyncValidator() { return Promise.resolve({'other': true}); }
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
describe('FormControl', () => {
it('should default the value to null', () => {
const c = new FormControl();
@ -977,6 +979,15 @@ export function main() {
expect(logger).toEqual(['control', 'group']);
});
it('should throw when sync validator passed into async validator param', () => {
const fn = () => new FormControl('', syncValidator, syncValidator);
// test for the specific error since without the error check it would still throw an error
// but
// not a meaningful one
expect(fn).toThrowError(
`expected the following validator to return Promise or Observable: ${syncValidator}. If you are using FormBuilder; did you forget to brace your validators in an array?`);
});
});
});
});