Skip to content

Commit

Permalink
fix(forms): Verify functions passed into async validators returns Obs…
Browse files Browse the repository at this point in the history
…ervable or Promise (#14053)
  • Loading branch information
Toxicable authored and mhevery committed Feb 3, 2017
1 parent 109f0d1 commit 774e1db
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions modules/@angular/forms/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,10 @@ export abstract class AbstractControl {
this._status = PENDING;
this._cancelExistingSubscription();
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})});
}
Expand Down
11 changes: 11 additions & 0 deletions modules/@angular/forms/test/form_control_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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?`);
});

});
});
});
Expand Down

0 comments on commit 774e1db

Please sign in to comment.