依赖于多个表单字段的 Angular2 验证器 [英] Angular2 validator which relies on multiple form fields
问题描述
是否可以创建一个可以使用多个值来确定我的字段是否有效的验证器?
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.
谢谢.
更新了示例代码...
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(/ddddd(-dddd)?/)) {
return { invalidZipCode: true };
}
}
}
推荐答案
为了重申其他人发布的方法,这就是我创建的 FormGroup
验证器的方式涉及多个群体.
To kind of reiterate on the methods other have posted, this is the way I've been creating FormGroup
validators that don't involve multiple groups.
对于此示例,只需提供 password
和 confirmPassword
字段的键名.
For this example, simply provide the key names of the password
and confirmPassword
fields.
// Example use of FormBuilder, FormGroups, and FormControls
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')})
为了让 Validators
接受参数,他们需要返回一个带有 FormGroup
或 FormControl
的 function
> 作为参数.在这种情况下,我正在验证 FormGroup
.
In order for Validators
to take parameters, they need to return a function
with either a FormGroup
or FormControl
as a parameter. In this case, I'm validating a FormGroup
.
function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
return (group: FormGroup): {[key: string]: any} => {
let password = group.controls[passwordKey];
let confirmPassword = group.controls[confirmPasswordKey];
if (password.value !== confirmPassword.value) {
return {
mismatchedPasswords: true
};
}
}
}
从技术上讲,如果我知道它们的键,我可以验证任何两个值,但我更喜欢将我的 Validators
命名为它们将返回的错误.可以修改该函数以采用第三个参数,该参数表示返回的错误的键名.
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.
2016 年 12 月 6 日更新(v2.2.4)
完整示例:https://embed.plnkr.co/ukwCXm/
这篇关于依赖于多个表单字段的 Angular2 验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!