【问题标题】:angular 12 custom validator validate one item is selected from arrayangular 12 自定义验证器验证从数组中选择的一项
【发布时间】:2022-11-05 21:33:47
【问题描述】:

嗨,我正在做一个Angular 12 应用程序使用材料.

我有这样的 FormGroup

form:FormGroup=new FormGroup({
    Id: new FormControl(null),
    Name: new FormControl('',Validators.required),
    Recipents: new FormControl('',[Validators.required, matchingEmailValidator()]),

    IsActive: new FormControl(true),
    ProcessorName: new FormControl('',Validators.required),
    Channel: new FormArray([],[ matchingCheckValidator()]),
  });

我有一个从数据库动态加载的复选框数组。

我想放一个自定义验证器验证是否至少选择了一个复选框。如果没有,请使用

<mat-error>This field is mandatory</mat-error>

我还有一个名为channelList 的变量,我的所有复选框都已选中。

 changeEventFunc( ob: MatCheckboxChange) {

    if (ob.checked) {
      this.channelList.push(ob.source.id);
    } else {
      this.channelList.forEach((element,index)=>{
        if(element== ob.source.id)
        {
         this.channelList.splice(index, 1);
        }
        }
      )}
  }

我定义了一个函数调用匹配检查验证器我想把验证放在哪里

    export function matchingCheckValidator(): ValidatorFn {
      return (control:AbstractControl) : ValidationErrors | null => {
        do the task
        }
      }
    }

这是我的 HTML

<mat-label><strong>Channel</strong></mat-label>
          <li *ngFor="let chanel of notification.NotificationChannelLogLevels">
            <mat-checkbox id= {{chanel.NotificationLogLevel.Id}} formArrayName="Channel"
            [checked]="chanel.IsActive"
             (change)="changeEventFunc($event)">
              {{chanel.NotificationLogLevel.Name}}
            </mat-checkbox>
          </li>

每次选中复选框时,我都需要运行自定义验证...

那可能吗?

谢谢

【问题讨论】:

    标签: validation angular-material formgroups angular-validator


    【解决方案1】:

    我认为除了使用自定义验证器功能之外别无他法。

    /**
     * Form Control Validator function to check if given `array` contains `control.value`
     * - If `array` is array of objects there is option to check value by object property (`key`)
     * @param array input array of primitive values (strings, numbers) OR objects
     * @param key (optional) object property/key
     * @returns `null` (**valid**) OR `{ doesntContain: true }` (**invalid**)
     */
    export function containsValueValidator(array: any[], key?: string): ValidatorFn {
      return (control: AbstractControl): ValidationErrors | null => {
        const valid = array.includes(control.value) || (key && array.includes(control.value[key]));
        const error: ValidationErrors = { doesntContain: true };
    
        return valid ? null : error;
      }
    }
    

    然后,在您想要动态应用此验证器的所有地方(如果您认为array 可以更改),您必须以正确的方式使用以下功能,例如:

    nameControl.clearValidators();
    nameControl.addValidators([Validators.required, Validators.maxLength(30), containsValueValidator(availableNamesFromDropdown)]);
    nameControl.setValue(currentName);
    nameControl.updateValueAndValidity();
    

    我希望这对将来的某些人有所帮助

    【讨论】:

      猜你喜欢
      • 2020-07-14
      • 2019-01-07
      • 2019-01-08
      • 1970-01-01
      • 2015-06-24
      • 2018-07-28
      • 2018-05-23
      • 2018-01-26
      • 2021-11-01
      相关资源
      最近更新 更多