首页 > 解决方案 > Angular 7 CustomValidator 永远无效

问题描述

我知道它可能是重复的,但重复并没有帮助我,因为我的验证器没有设置在FormGroup级别上。验证器工作。该res变量给了我一个true用户名何时被使用以及false何时不被使用。

验证器类:

    @Injectable({ providedIn: 'root' })
    export class AlreadyTakenValidator {

        static checkUsername(registrationService: RegistrationService) {
            return (control: AbstractControl) => {
                if (control.value == "") {
                    return null;
                }
                console.log(control.value)
                return registrationService.checkUsername(control.value).subscribe(res => {
                    console.log("ab " + res)
                    if(res) {
                        const usernameIsTaken = true;
                        console.log("usernameIsTaken " + usernameIsTaken)
                        return (usernameIsTaken);

                    } else {
                        console.log("bischt null kerle?" + res)
                        const usernameIsTaken = null;
                        console.log("usernameIsTaken " + usernameIsTaken)
                        return usernameIsTaken;
                    }

                    return res ? { usernameIsTaken: true } : null;
                });
            }
        }

我只是这样做以检查所有内容。通常最后一行return res ? { usernameIsTaken: true } : null;应该足够了。

我的TS:

    public buildForm() {
        this.registerForm = this.form.group({
          username: ['', [Validators.required, Validators.minLength(this.minLength), CustomValidators.validateCharacters, AlreadyTakenValidator.checkUsername(this.registrationService)]],
          email: ['', [Validators.required, Validators.email, CustomValidators.validateCharacters]],
          password: ['', [Validators.required]],
          passwordConfirmation: ['', Validators.required],
        }, {
            validator: MustMatch('password', 'passwordConfirmation')
          });

        this.personalForm = this.form.group({
          firstname: ['', [Validators.required, NoWhitespaceValidator()]],
          lastname: ['', [Validators.required, NoWhitespaceValidator()]],
          country: ['', [Validators.required]],
          dateOfBirth: ['', [Validators.required]],
          gender: ['', [Validators.required]],
        })
      }

AlreadyTakenValidator.checkUsername(this.registrationService)是问题所在。

在html中我只是调用:

          <mat-error class="invalid-feedback"
            *ngIf="f.username.touched && f.username.errors && f.username.errors.usernameIsTaken">
            Already taken
          </mat-error>
          <mat-error class="invalid-feedback"
            *ngIf="f.username.touched && f.username.errors && f.username.errors.required">
            {{ 'REGISTRATION.USERNAME' | translate }} {{ 'VALIDATION.REQUIRED' | translate }}
          </mat-error>
          <mat-error class="invalid-feedback"
            *ngIf="f.username.touched && f.username.errors && f.username.errors.minlength">
            {{ 'VALIDATION.MINLENGTH' | translate }} {{ minLength }}
          </mat-error>
          <mat-error class="invalid-feedback"
            *ngIf="f.username.touched && f.username.errors && f.username.errors.invalid_characters">
            {{ 'VALIDATION.CHARACTERS' | translate }}

此外,我的CustomValidators.validateCharacters验证器是自定义的,就像名字所说的那样,工作正常,但这个不是。

标签: angularangular-validation

解决方案


component.ts 代码

  checkUsername(control: AbstractControl) {
  return new Promise((resolve, reject) => {
  setTimeout(() => {
    if (control.value === 'super@secret.com') {
        resolve({ emailIsTaken: true })
    } else {resolve(null)}
  }, 2000)
 })
}

component.html 代码:

<form [formGroup]="form">
<input type="text" placeholder="Enter your email" formControlName="email"/>
<button type="submit" [disabled]="form.invalid">SEND</button>
<div *ngIf="form.get('email').pending">
<p>Form valid {{form.valid}}</p>
<p>Form invalid {{form.invalid}}</p> 
</form>

请在您的代码中明智地更改这是演示代码


推荐阅读