表单字段上是否可以有多个验证器?我尝试了这个,但它导致了一些奇怪的错误(字段永远无效,即使满足要求)
this.username = new Control('', Validators.minLength(5), Validators.required);
如何使用多个验证器?
答案 0 :(得分:54)
您可以使用Validators.compose()
this.username = new Control('',
Validators.compose(
[Validators.minLength(5), Validators.required]));
用于异步验证器使用
this.username = new Control('', null,
Validators.composeAsync(
[someAsyncValidator, otherAsyncValidator]));
异步验证器存在未解决的问题,尤其是同步验证器与异步验证器结合使用
要使同步验证程序与异步验证程序一起使用,请将同步验证程序包装在promises中并将它们组合为async valdiators,如
this.username = new Control('', null,
Validators.composeAsync([
(control:Control) => Promise.resolve(Validators.minLength(5)(control)),
(control:Control) => Promise.resolve(Validators.required(control)),
someAsyncValidator, otherAsyncValidator
]));
答案 1 :(得分:25)
此问题已得到解决
你可以制作一系列验证器
this.username = new FormControl('', [ Validators.minLength(5), Validators.required ]);
答案 2 :(得分:8)
我建议使用Validators.compose()方法组合所有非异步验证器,并为任何异步调用单独传入Validators.composeAsync()。
FormControl的构造函数arbase基本上如下:
使用FormBuilder的示例(随意使用直接控制):
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)
])
]
});
这有助于避免异步验证,直到非异步验证器有效(不包括初始检查,可以轻松处理,详见下文)。
所有组合示例(验证器,asyncValidators和debouncing):
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来破解去抖动的异步验证器:
this.someControl.debounceTime(300).subscribe(val => {
// async call...
});
我个人不建议在大多数情况下这样做,因为它会增加不必要的复杂情况。
注意:这应该有效,从最新版本的Angular(2&amp; 4)开始 写这篇文章。