From 94f84c5d7e1401818e4499625913e34a51804603 Mon Sep 17 00:00:00 2001 From: Toxicable Date: Sun, 22 Jan 2017 21:37:22 +1300 Subject: [PATCH] fix(forms): Verify functions passed into async validators returns Observable or Promise (#14053) --- modules/@angular/forms/src/model.ts | 4 ++++ modules/@angular/forms/test/form_control_spec.ts | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/modules/@angular/forms/src/model.ts b/modules/@angular/forms/src/model.ts index 53bb76604b..46075daaa0 100644 --- a/modules/@angular/forms/src/model.ts +++ b/modules/@angular/forms/src/model.ts @@ -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})}); } diff --git a/modules/@angular/forms/test/form_control_spec.ts b/modules/@angular/forms/test/form_control_spec.ts index 17dec961ae..b9b2b87dbe 100644 --- a/modules/@angular/forms/test/form_control_spec.ts +++ b/modules/@angular/forms/test/form_control_spec.ts @@ -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?`); + }); + }); }); });