asdsad
asdsad

Reputation: 201

How to reset angular form including custom validation errors.... None of recent answers helped ME

I have the following code....

this.authForm = new FormGroup({
      email: new FormControl("", [AuthValidator.required, Validators.email]),
      password: new FormControl("", [
        AuthValidator.required,
        AuthValidator.minLength(5)
      ])
    });

Now I want to reset this form, But When I call this.authForm.reset(), It throws error, can't read property trim of null....

I have the following Validators..

export class AuthValidator { 
    static required(c: AbstractControl): ValidationErrors | null {
        return (c.value as string).trim() ? null : { required: true };
    }

    static minLength(len: number): ValidatorFn {
        return (c: AbstractControl) => (c.value as string).trim().length < len ? { minlength: { requiredLength: len, actualLength: c.value.length } } : null; 
    }
}

How can I reset my form ???????????????? PLEASE HELP

I tried all the tricks like..

this.authForm.markAsPristine etc.. But it failed....

Upvotes: 1

Views: 912

Answers (1)

Johns Mathew
Johns Mathew

Reputation: 812

You are casting the control value to a string in your custom validator. However, it can be null or undefined after the form reset. Modify your validator to check for a valid string before using trim().

export class AuthValidator { 
    static required(c: AbstractControl): ValidationErrors | null {
        return (c.value && (c.value as string).trim()) ? null : { required: true };
    }

    static minLength(len: number): ValidatorFn {
        return (c: AbstractControl) => (c.value && (c.value as string).trim().length < len) ? { minlength: { requiredLength: len, actualLength: c.value.length } } : null; 
    }
}

Upvotes: 1

Related Questions