其他分享
首页 > 其他分享> > Angular响应式表单验证输入(跨字段验证、异步API验证)

Angular响应式表单验证输入(跨字段验证、异步API验证)

作者:互联网

一、跨字段验证

1、新增验证器

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

export const placeRevealedValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
  const fromPlace = control.get('fromPlace');
  const toPlace = control.get('toPlace');
  return fromPlace && toPlace && fromPlace.value === toPlace.value ? { 'placeRevealed': true } : null;
};

2、给 FormGroup 添加验证器

 initForm() {
    this.validateForm = this.fb.group(
      {
        Id: [0, [Validators.required]],
        fromPlace: [null, [Validators.required]],
        toPlace: [null, [Validators.required]],
        isValid: ['Y', [Validators.required]],
        language_Cd: ['zh-tw', [Validators.required]],
      },
      { validators: placeRevealedValidator }
    );
  }
  get fromPlace() {
    return this.validateForm.get('fromPlace') as any;
  }
  get toPlace() {
    return this.validateForm.get('toPlace') as any;
  }

3、页面判断(因为交叉验证设置在FormBuilder上,所以页面验证时使用FormBuilder值validateForm )

<nz-form-control>
              <nz-select nzAllowClear formControlName="toPlace" 
            class="inputs">
            <nz-option *ngFor="let item of place" [nzLabel]="item.routePlace" [nzValue]="item.routePlace">
            </nz-option>
          </nz-select>
          <div *ngIf="validateForm.errors?.['placeRevealed'] &&fromPlace.dirty &&toPlace.dirty"
            class="alert alert-danger">
          出發地和目的地不能相同
          </div>
          </nz-form-control>

一、异步验证

1、新增验证器

import { AbstractControl,  } from "@angular/forms";
import { catchError, map, of } from "rxjs";
import { DpaService } from "src/app/services/apis/dpa.service";

export class EmpIdRevealedValidators {

  static EmpIdValidator(dpaService: DpaService) {
      return (control: AbstractControl) => {
          if (!control.valueChanges) {
              return of(null);
          } else {
              return dpaService.GetUserByEmpId(control.value)
                .pipe(
                      map((isTaken: any) =>{
                       return (isTaken.length==0 ? { 'empIdRevealed': true } : null)
                      } ),
                      catchError(() => of(null))
                    );
          }
      }
  }
}

2、给 FormGroup 添加验证器

 initForm() {
    this.validateForm = this.fb.group({
      process: [this.process[0], [Validators.required]],
      bo: [null, [Validators.required]],
      site: [null, [Validators.required]],
      emplId:[null,{
        validators: [Validators.required],
        asyncValidators:EmpIdRevealedValidators.EmpIdValidator(this.dpaService),
        updateOn: 'blur' //鼠标移开后验证,还有change和submit
        }],
      isValid: ['Y', [Validators.required]],
    });
  }
  get emplId() {
    return this.validateForm.get('emplId') as any;
  }

3、页面判断(因为交叉验证设置在FormControl上,所以页面验证时使用FormControl值emplId)

<nz-form-item>
          <nz-form-label>工號</nz-form-label>
          <nz-form-control>
            <input nz-input [readonly]="this.apiAction==='Update'" formControlName="emplId"  class="inputs">           
          <div *ngIf="emplId.errors?.['empIdRevealed']&&emplId.dirty "
            class="alert alert-danger">
            工號不存在
          </div>
          </nz-form-control>
        </nz-form-item>

 

标签:null,return,验证,required,API,Validators,get,跨字段
来源: https://www.cnblogs.com/yyjspace/p/16434421.html