• Angular自定义异步验证器


    对名称进行重名异步判断
    <form nz-form [formGroup]="form">
        <p>
            <span class="group-name-control" nz-form-control>
        	    <input 
                     nz-input
                     placeholder="标签组名称" 
                     type="text" 
                     maxlength="15" 
                     formControlName="groupName">
                <span class="limit">{{ getFormControl('groupName').value.length }}/15</span>
            </span>
            <span  class="error pd-l-10" 
                         *ngIf="getFormControl('groupName').dirty
                                      && !getFormControl('groupName').valid 
                                      && getFormControl('groupName').errors?.required">
        	    请输入标签组名称
            </span>
            <span class="error pd-l-10" 
                *ngIf="getFormControl('groupName').dirty
                             && !getFormControl('groupName').valid
                             && getFormControl('groupName').errors?.type === 'repeat'">
                {{ getFormControl('groupName').errors.errMsg }}
            </span>
        </p>
    </form>  
    
        import {
            FormGroup,
            Validators,
            AbstractControl,
            ValidationErrors,
            AsyncValidatorFn
        } from '@angular/forms';
    
        this.form = this.fb.group({
            groupName:  ['', { Validators:[Validators.required, Validators.maxLength(15)], 
                         	        updateOn:  'blur' }],
         });
    
         this.form.controls['groupName'].setAsyncValidators(this.groupNameValidator(true, tag_group_name));
    
    
      /**
       * @desc 异步验证组名是否重复
       * @param {boolean} edit
       * @param {string} [groupName] - 组名
       */
      public groupNameValidator(edit: boolean, groupName?: string): AsyncValidatorFn {
        return async (control: AbstractControl): Promise<ValidationErrors | null> => {
          const value = control.value;
          if (!value) {
            return {
              valid: false,
              required: true
            };
          } else if (edit && value === groupName) {
            return null;
          } else {
            return this.updateTagsGroupService.checkGroupName(value)
            .toPromise()
            .then((res: object) => {
              const { status } = <any> res;
              if (status === 1) {
                return Promise.resolve({
                  valid: false,
                  type: 'repeat',
                  errMsg: '标签组名称重复,请重新输入'
                });
              }
              return null;
            });
          }
        };
      }
    
    //
    
    
    
    性能上的注意事项

    默认情况下,每当表单值变化之后,都会执行所有验证器。对于同步验证器,没有什么会显著影响应用性能的地方。不过,异步验证器通常会执行某种 HTTP 请求来对控件进行验证。如果在每次按键之后都发出 HTTP 请求会给后端 API 带来沉重的负担,应该尽量避免。

    我们可以把 updateOn 属性从 change(默认值)改成 submitblur 来推迟表单验证的更新时机。

    new FormControl('', {updateOn: 'blur'}); // 失去焦点时验证
    
  • 相关阅读:
    [leetcode]Remove Nth Node From End of List @ Python
    [leetcode]Swap Nodes in Pairs @ Python
    [leetcode]Linked List Cycle II @ Python
    [leetcode]Linked List Cycle @ Python
    [leetcode]LRU Cache @ Python
    [leetcode]Reorder List @ Python
    [leetcode]Insertion Sort List @ Python
    [leetcode]Sort List @ Python
    [leetcode]3Sum Closest @ Python
    [elk]elasticsearch实现冷热数据分离
  • 原文地址:https://www.cnblogs.com/chenfengami/p/12783668.html
Copyright © 2020-2023  润新知