0

HTML

 <form nz-form [formGroup]="formGroup">
        <nz-form-item>
          <nz-form-label nzFor="username">
            <span translate>Username</span>
          </nz-form-label>
          <nz-form-control nzHasFeedback>
            <input nz-input name="username" type="text" id="username" formControlName="username"
              [placeholder]="'Enter Username' | translate" (keydown.space)="$event.preventDefault()" />
            <nz-form-explain *ngIf="
              (formGroup.get('username')?.dirty && formGroup.get('username')?.errors) ||
              formGroup.get('username')?.pending
            ">
              <ng-container *ngIf="formGroup.get('username')?.hasError('required')">
                Username is required
              </ng-container>
              <ng-container *ngIf="formGroup.get('username')?.hasError('duplicated')">
                Username already exists. Please try different username
              </ng-container>
              <ng-container *ngIf="formGroup.get('username')?.pending">
                Validating...
              </ng-container>
            </nz-form-explain>
          </nz-form-control>
        </nz-form-item>
</form>

***TS****

import { FormGroup, FormBuilder, Validators, FormControl, ValidationErrors } from '@angular/forms';



 userNameAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (control.value === 'JasonWood') {
          observer.next({ error: true, duplicated: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  createFormGroup(data?: Partial<User>) {
    const dataObj = {
      id: [data && data.id],
      username: [
        {
          value: (data && data.username) || '',
          disabled: data instanceof User
        },
        [Validators.required], 
[this.userNameAsyncValidator]
      ]
    }

    return this.fb.group(dataObj);
}

user.module

imports: [
    CommonModule,
    UsersRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    PageTableFilterModule,
    CellRenderersModule,
    NzDrawerModule,
    NzFormModule,
    NzInputModule,
    NzSelectModule,
    NzDividerModule
    ]

how to fix the error: ERROR TypeError: Cannot read property 'validate' of undefined.

What I want is username have a validation which is already exists and username is required.

I added the userNameAsyncValidator, after I added in username then it start causing an error which is the ERROR TypeError: Cannot read property 'validate' of undefined. but when I try to remove the userNameAsyncValidator in username it doesn't have any error.

how to fix it?

ERROR:

    at normalizeAsyncValidator (forms.js:930)
    at Array.map (<anonymous>)
    at composeAsyncValidators (forms.js:2150)
    at coerceToAsyncValidator (forms.js:2501)
    at new FormControl (forms.js:3236)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder.control (forms.js:6462)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._createControl (forms.js:6502)
    at forms.js:6488
    at Array.forEach (<anonymous>)
    at FormBuilder.push../node_modules/@angular/forms/fesm5/forms.js.FormBuilder._reduceControls (forms.js:6487)```
7
  • Can you show imports in your TS file?! Commented Apr 30, 2020 at 4:44
  • @SakkeerA done sir. I added the imports also the user.module Commented Apr 30, 2020 at 4:56
  • Does this.userNameAsyncValidator validator getting triggered? Commented Apr 30, 2020 at 5:07
  • @Chellappanவ when I try to run this is the error ERROR TypeError: Cannot read property 'validate' of undefined Commented Apr 30, 2020 at 5:11
  • Can you remove this.userNameAsyncValidator from validators array and check? Commented Apr 30, 2020 at 5:25

3 Answers 3

1

Since this.userNameAsyncValidator is async validator add userNameAsyncValidator as third paramter to username control. another change is move your form creation inside ngOnInit or constructo like this:

Try this:

 constructor(private fb: FormBuilder) {
    this.validateForm = this.createFormGroup();
  }

 createFormGroup(data?: Partial<User>) {
        const dataObj = {
          id: [data && data.id],
          username: [
            {
              value: (data && data.username) || '',
              disabled: data instanceof User
            },
            [Validators.required],
            [this.userNameAsyncValidator]
          ]
        }

        return this.fb.group(dataObj);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

You are injecting form builder inside contructor and trying to access form builder before it's get created if you move your form creation insde ngOnInit or contrctor it will not throw any error
I just comment the code on the constructor. inside my constructor is empty. have you fix it?
1

In my case, when upgrading to Angular 11. The following validators array was breaking the unit tests:

[, Validators.required]

Notice there is nothing before the comma. Removing the comma fixed the issue for me.

Comments

0

In my case i had to remove FormsModule and ReactiveFormModule from imports to work

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.