Angular2验证依赖于多个表单域 [英] Angular2 validator which relies on multiple form fields

查看:170
本文介绍了Angular2验证依赖于多个表单域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能建立一个验证器可同时使用多个值来决定,如果我的领域是有效的?

例如。如果客户的preferred接触的方法是通过电子邮件,然后电子邮件字段应符合规定。

感谢。


更新,其中例如code ...


 进口{组件,查看}从'angular2 / angular2';
进口{FormBuilder,验证,formDirectives,ControlGroup}从'angular2 /表格;@零件({
    选择:'以客户为基础,
    viewInjector:[FormBuilder]
})
@视图({
    templateUrl:应用程序/组件/ customerBasic / customerBasic.html',
    指令:[formDirectives]
})
出口类CustomerBasic {
    customerForm:ControlGroup;    构造器(制造商:FormBuilder){
        this.customerForm = builder.group({
            名字: [''],
            姓: [''],
            validateZip:'是'],
            拉链code:['',this.zip codeValidator受]
            //我只是想用当validateZip控制设置为'yes'下面的功能验证
        });
    }    拉链codeValidator受(控制){
        (!control.value.match(/ \\ D \\ D \\ D \\ D \\ D(? - \\ D \\ D \\ D \\ D)/)){如果
            返回{invalidZip code:真正};
        }
    }}


解决方案

要在其他已经公布的方法那种重申,这是我一直在创建方式 ControlGroup 不涉及多个组的验证。

在这个例子中,只需提供密码的按键名称 confirmPassword 字段。

  //使用示例FormBuilder的,ControlGroups和控制
this.registrationForm = fb.group({
  出生日期:['',Validators.required]
  电子邮件:['',Validators.compose([Validators.required,emailValidator])],
  密码:['',Validators.required]
  confirmPassword:['',Validators.required]
  姓:['',Validators.required]
  名字:['',Validators.required]
},{验证:matchingPasswords('密码','confirmPassword')})

为了为校验来带参数,他们需要返回一个函数带是 ControlGroup 控制作为参数。在这种情况下,我确认一个 ControlGroup

 函数matchingPasswords(PasswordKey的:字符串,confirmPasswordKey:字符串){
  返回(组:ControlGroup):{[键:字符串]:任何} => {
    让密码= group.controls [PasswordKey的];
    让confirmPassword = group.controls [confirmPasswordKey]    如果(password.value!== confirmPassword.value){
      返回{
        mismatchedPasswords:真
      };
    }
  }
}

从技术上讲,我可以证实任意两个值,如果我知道他们的钥匙,但我preFER来命名我的校验一样,他们将返回错误。该功能可以修改采取重新presents错误的键名返回的第三个参数。

下面是一个例子: https://plnkr.co/edit/ukwCXm?p=$p$pview

Is it possible to create a validator which can use multiple values to decide if my field is valid?

e.g. if the customer's preferred contact method is by email then the email field should be required.

Thanks.


Updated with example code...


import {Component, View} from 'angular2/angular2';
import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';

@Component({
    selector: 'customer-basic',
    viewInjector: [FormBuilder]
})
@View({
    templateUrl: 'app/components/customerBasic/customerBasic.html',
    directives: [formDirectives]
})
export class CustomerBasic {
    customerForm: ControlGroup;

    constructor(builder: FormBuilder) {
        this.customerForm = builder.group({
            firstname: [''],
            lastname: [''],
            validateZip: ['yes'],
            zipcode: ['', this.zipCodeValidator] 
            // I only want to validate using the function below if the validateZip control is set to 'yes'
        });
    }

    zipCodeValidator(control) {
        if (!control.value.match(/\d\d\d\d\d(-\d\d\d\d)?/)) {
            return { invalidZipCode: true };
        }
    }

}

解决方案

To kind of reiterate on the methods other have posted, this is the way I've been creating ControlGroup validators that don't involve multiple groups.

For this example, simply provide the key names of the password and confirmPassword fields.

// Example use of FormBuilder, ControlGroups, and Controls
this.registrationForm= fb.group({
  dob: ['', Validators.required],
  email: ['', Validators.compose([Validators.required,  emailValidator])],
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required]
}, {validator: matchingPasswords('password', 'confirmPassword')})

In order for Validators to take parameters, they need to return a function with either a ControlGroup or Control as a parameter. In this case, I'm validating a ControlGroup.

function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
  return (group: ControlGroup): {[key: string]: any} => {
    let password = group.controls[passwordKey];
    let confirmPassword = group.controls[confirmPasswordKey];

    if (password.value !== confirmPassword.value) {
      return {
        mismatchedPasswords: true
      };
    }
  }
}

Technically, I could have validated any two values if I knew their keys, but I prefer to name my Validators the same as the error they will return. The function could be modified to take a third parameter that represents the key name of the error returned.

Here's an example: https://plnkr.co/edit/ukwCXm?p=preview

这篇关于Angular2验证依赖于多个表单域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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