Angular2 FormBuilder验证器:至少需要填充组中的一个字段 [英] Angular2 FormBuilder Validatiors: require at least one field in a group to be filled

查看:175
本文介绍了Angular2 FormBuilder验证器:至少需要填充组中的一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个收集电话号码(移动电话,个人电话和其他电话)的表格.我至少需要填充输入.我正在尝试使用Angular2 FormBuilder.

I have a form where I'm collecting phone numbers (mobile, personal, other). I need to have at least input populated. I'm trying to use Angular2 FormBuilder.

经过大量研究,我在解决这个问题时遇到了问题.我知道我可以使用其他方法来做到这一点,但是我想知道是否可以使用FormBuilder Validators.如果我添加"Validators.required",则必须填写所有3个字段.有什么建议或想法吗?

After much research I'm having a problem getting my head around this problem. I know I can do it using other methods but I was wondering if it's possible using FormBuilder Validators. If I add "Validators.required" then all 3 fields are required. Any suggestions or ideas?

phone: this._fb.group(
                    {
                        other: [''],
                        personal: [''],
                        mobile: [''],
                    }

基于"JB Nizet"的提示,这是我必须实现的功能:

Base on the hint from " JB Nizet", here's what I had to implement to make it work:

我的组验证器(仍然需要调整):

My group Validator (it still needs tweaking):

static phoneExists(group: FormGroup): { [key: string]: any } {

    if (null != group) {
        var other: AbstractControl = group.controls['other'];
        var mobile: AbstractControl = group.controls['mobile'];
        var personal: AbstractControl = group.controls['personal'];
        var data: Object = group.value;

        return (
            (other.valid && isEmptyInputValue(other.value))
            && (mobile.valid && isEmptyInputValue(mobile.value))
            && (personal.valid && isEmptyInputValue(personal.value))
            )
            ? { 'required': true }
            : null;
    }
}

我的小组更改:

phone: this._fb.group(
                    {
                        other: [''],
                        personal: [''],
                        mobile: [''],
                    },
                    { validator: MyValidators.phoneExists }
                )

花了我一段时间,但关键是添加了关键字验证器",这将导致组验证器触发.

It took me a while, but the key is to add the key word "validator" and it will cause the group validator to fire.

在HTML中,我添加了以下内容:

In the HTML i added the following:

<small *ngIf="!myForm.controls.profile.controls.phone.valid" class="text-danger">
                                        At least one phone is required.
                                    </small>

我希望这对其他人有帮助.

I hope this help anyone else.

推荐答案

我使用了atLeastOne函数,该函数基于任何现有验证器创建自定义验证器:

I use an atLeastOne function that creates a custom validator based on any existing validator:

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

export const atLeastOne = (validator: ValidatorFn) => (
  group: FormGroup,
): ValidationErrors | null => {
  const hasAtLeastOne =
    group &&
    group.controls &&
    Object.keys(group.controls).some(k => !validator(group.controls[k]));

  return hasAtLeastOne ? null : { atLeastOne: true };
};

的优点是您可以将任何验证器与它一起使用,而不仅仅是Validators.required.

The beauty is that you can use any validator with it and not just Validators.required.

在OP的情况下,它将像这样使用:

In OP's case, it'll be used like this:

{
  phone: this._fb.group({
    other: [''],
    personal: [''],
    mobile: [''],
  }, { validator: atLeastOne(Validators.required) })
}

这篇关于Angular2 FormBuilder验证器:至少需要填充组中的一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆