【问题标题】:How to add custom unique validator for form values in angular reactive form?如何为角度反应形式的表单值添加自定义唯一验证器?
【发布时间】:2025-12-09 02:10:01
【问题描述】:

我想添加一个自定义唯一验证器,该验证器将验证所有标签字段值是否唯一。 (I) 当我更改表单值时,this.form 的值在传入CustomValidator.uniqueValidator(this.form) 后会发生变化。如何解决这个问题? (II) 有没有什么方法可以不使用任何包来做到这一点?

注意:表单在加载时具有默认值。这是屏幕截图。

this.form = this.fb.group({
      fields: this.fb.array([])
    });

private addFields(fieldControl?) {
return this.fb.group({
  label: [
    {value: fieldControl ? fieldControl.label : '', disabled: this.makeComponentReadOnly}, [
    Validators.maxLength(30), CustomValidator.uniqueValidator(this.form)
    ]],
  isRequired: [
    {value: fieldControl ? fieldControl.isRequired : false, disabled: this.makeComponentReadOnly}],
  type: [fieldControl ? fieldControl.type : 'text']
});

}

  static uniqueValidator(form: any): ValidatorFn | null {
return (control: AbstractControl): ValidationErrors | null => {
  console.log('control..: ', control);
  const name = control.value;

  if (form.value.fields.filter(v => v.label.toLowerCase() === control.value.toLowerCase()).length > 1) {
    return {
      notUnique: control.value
    };
  } else {
    return null;
  }

}; }

【问题讨论】:

  • 我认为你完全忽略了这一点。电子邮件地址的格式不可能与电话号码的格式相同。为什么不使用模式验证器来确保名称没有@ 或数字,并确保电子邮件是电子邮件,电话是电话。
  • 我建议@rxweb/reactive-form-validators 做这样的工作。相同的套餐不提供。其他有用的验证。
  • 如果“添加字段”按钮将一组全新的相同字段添加到 FormArray 中,您需要遍历 FormArray 中的每个 FormGroup 并确保 FormArray 中没有重复项。
  • 实际上,根据条件和特征,不应该对其中任何一个单独进行任何验证,除非只有一个没有两个表单字段不能具有相同的值。现在我只是在提交之前比较表单值。如果有另一种没有包装的解决方案,那么它会很有帮助。感谢 cmets。

标签: javascript angular validation angular-reactive-forms


【解决方案1】:

在现实生活中,用户名或电子邮件属性被检查为唯一。这将是一个很长的答案,我希望你能跟进。我将展示如何检查用户名的唯一性。

要检查数据库,您必须创建一个服务来发出请求。所以这个验证器将是异步验证器,它将被写入类中。这个类将通过依赖注入技术与服务进行通信。

首先你需要设置HttpClientModule。在 app.module.ts 中

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, YourOthersModule , HttpClientModule],
  providers: [],
  bootstrap: [AppComponent],
})

然后创建一个服务

 ng g service Auth //named it Auth

在这个 auth.service.ts 中

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}
  userNameAvailable(username: string) {
 // avoid type "any". check the response obj and put a clear type
    return this.http.post<any>('https://api.angular.com/username', {
      username:username,
    });
  }
}

现在创建一个类 ng g class UniqueUsername 并在这个类中:

import { Injectable } from '@angular/core';
import { AsyncValidator, FormControl } from '@angular/forms';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { AuthService } from './auth.service';
// this class needs to use the dependency injection to reach the http client to make an api request
// we can only access to http client with dependecny injection system
// now we need to decorate this class with Injectable to access to AuthService
@Injectable({
  providedIn: 'root',
})
export class UniqueUsername implements AsyncValidator {
  constructor(private authService: AuthService) {}
  //this will be used by the usernamae FormControl
  //we use arrow function cause this function will be called by a 
  //different context, but we want it to have this class' context 
  //because this method needs to reach `this.authService`. in other context `this.authService` will be undefined.
  // if this validator would be used by the FormGroup, you could use 
  "FormGroup" type.
  //if you are not sure you can  use type "control: AbstractControl"
  //In this case you use it for a FormControl
  


   validate = (control: FormControl) => {
        const { value } = control;
        return this.authService.userNameAvailable(value).pipe(
        //errors skip the map(). if we return null, means we got 200 response code, our request will indicate that username is available
        //catchError will catch the error
          map(() => {
            return null;
          }),
          catchError((err) => {
            console.log(err);
         //you have to console the error to see what the error object is. so u can 
         // set up your logic based on properties of the error object.
       // i set as err.error.username as an  example. your api server might return an error object with different properties.
            if (err.error.username) {
       //catchError has to return a new Observable and "of" is a shortcut
       //if err.error.username exists, i will attach `{ nonUniqueUsername: true }` to the formControl's error object.
               return of({ nonUniqueUsername: true });
            }
            return of({ noConnection: true });
          })
        );
      };
    }

到目前为止,我们处理了服务和异步类验证器,现在我们在表单上实现它。我将只有用户名字段。

    import { Component, OnInit } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    import { UniqueUsername } from '../validators/unique-username';
    
    @Component({
      selector: 'app-signup',
      templateUrl: './signup.component.html',
      styleUrls: ['./signup.component.css'],
    })
    export class SignupComponent implements OnInit {
      authForm = new FormGroup(
        {
          // async validators are the third arg
          username: new FormControl(
            '',
            [
              Validators.required,
              Validators.minLength(3),
              Validators.maxLength(20),
              Validators.pattern(/^[a-z0-9]+$/),
            ],
         // async validators are gonna run after all sync validators 
         successfully completed running because async operations are 
         expensive.
            this.uniqueUsername.validate
          ),
        },
        { validators: [this.matchPassword.validate] }
      );
      constructor(
        private uniqueUsername: UniqueUsername
      ) {}
    
  
    //this is used inside the template file. you will see down below
    showErrors() {
        const { dirty, touched, errors } = this.control;
        return dirty && touched && errors;
      }
      ngOnInit(): void {}
    }

最后一步是向用户显示错误:在表单组件的模板文件中:

<div class="field">
  <input  formControl="username"  />
  <!-- this is where you show the error to the client -->
  <!-- showErrors() is a method inside the class -->
  
  <div *ngIf="showErrors()" class="ui pointing red basic label">
    <!-- authForm.get('username') you access to the "username" formControl -->
    <p *ngIf="authForm.get('username').errors.required">Value is required</p>
    <p *ngIf="authForm.get('username').errors.minlength">
      Value must be longer
      {{ authForm.get('username').errors.minlength.actualLength }} characters
    </p>
    <p *ngIf="authForm.get('username').errors.maxlength">
      Value must be less than {{ authForm.get('username').errors.maxlength.requiredLength }}
    </p>
    <p *ngIf="authForm.get('username').errors.nonUniqueUsername">Username is taken</p>
    <p *ngIf="authForm.get('username').errors.noConnection">Can't tell if username is taken</p>
  </div>
</div>

【讨论】:

    【解决方案2】:

    您可以在父元素(ngModelGroup 或表单本身)上创建验证器指令:

    import { Directive } from '@angular/core';
    import { FormGroup, ValidationErrors, Validator, NG_VALIDATORS } from '@angular/forms';
    
    @Directive({
      selector: '[validate-uniqueness]',
      providers: [{ provide: NG_VALIDATORS, useExisting: UniquenessValidator, multi: true }]
    })
    export class UniquenessValidator implements Validator {
    
      validate(formGroup: FormGroup): ValidationErrors | null {
        let firstControl = formGroup.controls['first']
        let secondControl = formgroup.controls['second']
        // If you need to reach outside current group use this syntax:
        let thirdControl =  (<FormGroup>formGroup.root).controls['third']
    
        // Then validate whatever you want to validate
        // To check if they are present and unique:
        if ((firstControl && firstControl.value) &&
            (secondControl && secondControl.value) &&
            (thirdContreol && thirdControl.value) &&
            (firstControl.value != secondControl.value) &&
            (secondControl.value != thirdControl.value) &&
            (thirdControl.value != firstControl.value)) {
          return null;
        }
    
        return { validateUniqueness: false }
      }
    
    }
    

    您可能可以简化该检查,但我认为您明白了。 我没有测试这段代码,但如果你想看一下,我最近在这个项目中只用了 2 个字段做了类似的事情:

    https://github.com/H3AR7B3A7/EarlyAngularProjects/blob/master/modelForms/src/app/advanced-form/validate-about-or-image.directive.ts

    不用说,像这样的自定义验证器是相当特定于业务的,在大多数情况下很难使其可重用。更改表格可能需要更改指令。还有其他方法可以做到这一点,但这确实有效,而且是一个相当简单的选择。

    【讨论】:

      最近更新 更多