简体   繁体   English

Angular 异步验证器检查数据库中输入的唯一性

[英]Angular async validator check unicity of input in database

I have an <input> where the user enter a value that is supposed to be unique in database.我有一个<input> ,用户在其中输入一个应该在数据库中唯一的值。 I want to check dynamically in the front-end if that value is unique or not.我想在前端动态检查该值是否唯一。

I want also to display an error message if the value is already stored in database.如果值已经存储在数据库中,我还想显示一条错误消息。

You can use a custom async validator to do that.您可以使用自定义异步验证器来执行此操作。 Let's say you want to check that the name is unique.假设您要检查名称是否唯一。 First, create a new file for the async validator:首先,为异步验证器创建一个新文件:

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

    constructor(private nameService: NameService) { }

    CheckNameValidator(): AsyncValidatorFn {
        return (control: AbstractControl): Observable<{ [key: string]: boolean } | null> => {
            return this.nameService.nameExists(control.value)
                .pipe(
                    map(valueExists => {
                        if (valueExists) {
                            return { nameExists: true };
                        }
                        return null;
                    }
                    )
                )
        }
    }

The validator is a service where you import the service nameService where you can call your api.验证器是一个服务,您可以在其中导入服务 nameService,您可以在其中调用 api。 The api must return if the value is present or not.如果值存在与否,api 必须返回。 Then, in the controller:然后,在 controller 中:


export class MainComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private nameValidator: NameValidator 
    ) {}

public formGroup: FormGroup;

ngOnInit(): void { 
  
    this.formGroup = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(3)], [this.nameValidator.CheckNameValidator()]]
    }, {updateOn: 'blur'});
  }

When you build your formgroup, each form control can hold a value, an array of validators, and an array of async validators.构建表单组时,每个表单控件都可以保存一个值、一个验证器数组和一个异步验证器数组。 That's where i put the call to the asyn validator service.这就是我调用异步验证器服务的地方。

Notice the {updateOn: 'blur'} , if you do not write this, the update to check the validators is on change, so you make way too many api calls.注意{updateOn: 'blur'} ,如果你不写这个,检查验证器的更新正在改变,所以你做了太多的 api 调用。 With onBlur the api call is done onblur => performance gain.使用 onBlur api 调用完成 onblur => 性能提升。

If you use angular material, your view should look something like this:如果您使用 angular 材料,您的视图应如下所示:

<ng-container [formGroup]="formGroup">
    <mat-form-field class="field-full-width">
        <input matInput placeholder="Name" formControlName="name">
        <mat-error *ngIf="formGroup.controls['name'].errors?.nameExists">This name is already in use</mat-error>
    </mat-form-field>
</ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM