2
votes

I have a Data-Driven Form in angular 2. And in one of the control i have a custom validator. If i am using this.myForm.reset() while the control on which the validator has been applied having some value, the validator cracks up, and throws an error.

While if i'm not using this.myForm.reset() method anywhere, the custom validator works just great!

The custom validator uses a package installed by npm in the angular component. The validator is as follows:

phoneNumberValidator (control: FormControl): {[s: string]: boolean} {
   if (!validator.isMobilePhone((<string>control.value), 'en-IN')) {
     return {phoneNumberValidator: true};
   }
   return null;
}

And i'm using the validator as follows:

'phoneNumber': new FormControl('', [
     Validators.required,
     Validators.maxLength(14),
     this.phoneNumberValidator
])

Error message: Error message

As I've mentioned, the validator is working fine without myform.reset() The npm package I'm using is this

I've tried to use ngForm, but i guess it is for Template-Driven forms.

1

1 Answers

2
votes

It seems like the phoneNumberValidator plugin that you're using needs phoneNumber control should have at least empty string. So you set up that value to empty string while resetting a form.

this.myForm.reset({'phoneNumber': ''})
//OR
//this.myForm.resetForm({'phoneNumber': ''})