【发布时间】:2016-05-11 16:36:09
【问题描述】:
一个表单域可以有多个验证器吗?我试过这个,但它导致了一些奇怪的错误(字段永远无效,即使满足要求)
this.username = new Control('', Validators.minLength(5), Validators.required);
如何使用多个验证器?
【问题讨论】:
标签: typescript angular
一个表单域可以有多个验证器吗?我试过这个,但它导致了一些奇怪的错误(字段永远无效,即使满足要求)
this.username = new Control('', Validators.minLength(5), Validators.required);
如何使用多个验证器?
【问题讨论】:
标签: typescript angular
您可以使用 Validators.compose() 组合验证器
this.username = new Control('',
Validators.compose(
[Validators.minLength(5), Validators.required]));
供异步验证器使用
this.username = new Control('', null,
Validators.composeAsync(
[someAsyncValidator, otherAsyncValidator]));
异步验证器存在一些未解决的问题,尤其是同步验证器与异步验证器结合时不起作用
要使同步验证器与异步验证器一起工作,请将同步验证器包装在 Promise 中并将它们组合为异步验证器,例如
this.username = new Control('', null,
Validators.composeAsync([
(control:Control) => Promise.resolve(Validators.minLength(5)(control)),
(control:Control) => Promise.resolve(Validators.required(control)),
someAsyncValidator, otherAsyncValidator
]));
【讨论】:
这个问题已经解决了
你可以创建一个验证器数组
this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]);
【讨论】:
compose有什么区别?
我建议使用 Validators.compose() 方法来组合所有非异步验证器,并为任何异步调用单独传入 Validators.composeAsync()。
FormControl 的构造函数参数如下:
使用 FormBuilder 的示例(随意直接使用 Control):
this.acctForm = this.fb.group({
'name': [
'',
Validators.compose([
Validators.required, Validators.minLength(2), Validators.maxLength(20), Validators.pattern('[a-zA-Z]')
])
],
'cellNumber': [
'',
Validators.compose([
Validators.required, Validators.pattern('[0-9]{10}')
]),
Validators.composeAsync([
this.checkPhoneValid.bind(this)
])
]
});
这有助于避免异步验证,直到非异步验证器有效(不包括初始检查,它很容易处理,请参见下文)。
一切组合示例(验证器、异步验证器和去抖动):
import { Component, Injectable, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
@Component({
selector: 'app-sandbox',
templateUrl: './sandbox.component.html',
providers: []
})
export class FormControlsDemoComponent implements OnInit {
private debouncedTimeout;
public acctForm: FormGroup;
constructor(private http: Http, private fb: FormBuilder) {
// @note Http should never be directly injected into a component, for simplified demo sake...
}
ngOnInit() {
this.acctForm = this.fb.group({
// Simple Example with Multiple Validators (non-async)
'name': [
'',
Validators.compose([
Validators.required, Validators.minLength(2), Validators.maxLength(20), Validators.pattern('[a-zA-Z]')
])
],
// Example which utilizes both Standard Validators with an Async Validator
'cellNumber': [
'',
Validators.compose([
Validators.required, Validators.minLength(4), Validators.maxLength(15), Validators.pattern('[0-9]{10}')
]),
Validators.composeAsync([
this.checkPhoneValid.bind(this) // Important to bind 'this' (otherwise local member context is lost)
/*
@note if using a service method, it would look something like this...
@example:
this.myValidatorService.phoneUniq.bind(this.myValidatorService)
*/
])
],
// Example with both, but Async is implicitly Debounced
'userName': [
'',
Validators.compose([
Validators.required, Validators.minLength(4), Validators.maxLength(15), Validators.pattern('[a-zA-Z0-9_-]')
]),
Validators.composeAsync([
this.checkUserUniq.bind(this) // @see above async validator notes regarding use of bind
])
]
});
}
/**
* Demo AsyncValidator Method
* @note - This should be in a service
*/
private checkPhoneValid(control: AbstractControl): Promise<any> {
// Avoids initial check against an empty string
if (!control.value.length) {
Promise.resolve(null);
}
const q = new Promise((resolve, reject) => {
// determine result from an http response or something...
let result = true;
if (result) {
resolve(null);
} else {
resolve({'phoneValidCheck': false});
}
});
return q;
}
/**
* Demo AsyncValidator Method (Debounced)
* @note - This should be in a service
*/
private checkUserUniq(control: AbstractControl): Promise<any> {
// Avoids initial check against an empty string
if (!control.value.length) {
Promise.resolve(null);
}
clearTimeout(this.debouncedTimeout);
const q = new Promise((resolve, reject) => {
this.debouncedTimeout = setTimeout(() => {
const req = this.http
.post('/some/endpoint', { check: control.value })
.map(res => {
// some handler logic...
return res;
});
req.subscribe(isUniq => {
if (isUniq) {
resolve(null);
} else {
resolve({'usernameUnique': false });
}
});
}, 300);
});
return q;
}
}
有些人喜欢通过绑定到控件的 Observable valueChanges 来破解 debounced async 验证器,如下所示:
this.someControl.debounceTime(300).subscribe(val => {
// async call...
});
我个人不建议在大多数情况下这样做,因为它会增加不必要的复杂性。
注意:从最新版本的 Angular(2 和 4)开始,这应该可以工作,因为 写这篇文章。
【讨论】:
Promise.resolve(null)。