如何为角形反应形式的形式值添加自定义唯一验证器?

问题描述

我想添加一个自定义的唯一验证器,它将验证所有标签字段的值都是唯一的。 (I)当我更改表单值时,this.form的值会在 CustomValidator.uniqueValidator(this.form)中传递后更改。如何解决这个问题? (II)有没有不用任何包装的方法吗?

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

enter image description here

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;
  }

}; }

解决方法

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

要检查数据库,您必须创建一个服务以发出请求。因此此验证器将为异步验证器,并将其编写为类。此类将通过依赖项注入技术与服务进行通信。

首先需要设置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>
,

您可以在父元素(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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...