Reputation: 200
I have defined a async validator function like this.
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'some_text') {
resolve({ shouldBeUnique: true });
}
reject(null);
}, 2000);
});
}
Its throwing below error (may be on reject)
Cannot read property 'ngOriginalError' of null
How to get rid of this error? Thanks
Plnkr : https://embed.plnkr.co/VSHXGKiMGUWEhy8neyXU/
Upvotes: 0
Views: 1393
Reputation: 45121
Generally if you reject a Promise you should better reject it with an Error
reject(new Error('User is not vikash (whatever descriptive message what went wrong)'));
EDIT Since you are trying to implement async validator you need to resolve
a Promise with null
not to reject it to indicate validation was ok.
static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'some_text') {
resolve({ shouldBeUnique: true });
} else {
resolve(null); // resolve
}
}, 2000);
});
}
Upvotes: 3
Reputation: 3211
In angular form validation, when the field is valid you should pass null. It's a little bit confusing but that's how it goes. You can read more about here and here.
I'm attaching plunker I've forked from you. I've only changed that null will be return when the filed is valid, and ValidationErrors when it's invalid. Also to be more clear about the filed validation status Iv'e added to the html the errors object of the filed.
https://embed.plnkr.co/t0gniM/
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
Please open developer console to chek the exception <br>
Type anything and click anywhere other than the textbox<br><br>
<form [formGroup]="formObj">
<input type="text" id="username" formControlName="username" placeholder="Username" />
{{formObj.controls['username'].errors|json}}
</form>
</div>
`,
})
export class App {
name:string;
shouldBeUnique(control:AbstractControl):Promise<ValidationErrors|null>{
return new Promise((resolve, reject) => {
setTimeout(() => {
if (control.value === 'vikash') {
console.log('---matched--');
resolve(null);
}else{
resolve({ shouldBeUnique: true });
}
}, 1000);
});
}
formObj = new FormGroup({
username: new FormControl('', [
Validators.required
], [
this.shouldBeUnique
])
});
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@NgModule({
imports: [ BrowserModule,FormsModule,ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Hopes it's help's.
Upvotes: 1