好吧,有一个
long discussion on github,结果如下:我们必须实现自己的验证器.
原文链接:https://www.f2er.com/angularjs/142401.html这是我到目前为止使用的:
import { ValidatorFn,AsyncValidatorFn,Validators as V,FormControl } from '@angular/forms'; // the need in this validators is the non-trimming angular standard behavior // see https://github.com/angular/angular/issues/8503 export class Validators { public static required(control: FormControl) { if (!control.value || typeof control.value === 'string' && !control.value.trim()) { return { required: true }; } return null; } public static minLength(length: number): ValidatorFn { return (control: FormControl) => { if (!control.value || typeof control.value === 'string' && control.value.trim().length < length) { return { minlength: true }; } return null; }; } public static maxLength(length: number): ValidatorFn { return (control: FormControl) => { if (control.value && typeof control.value === 'string' && control.value.trim().length > length) { return { maxlength: true }; } return null; }; } public static pattern(pattern: string): ValidatorFn { return V.pattern(pattern); } public static minAmount(amount: number): ValidatorFn { return (control: FormControl) => { if (control.value && control.value.length < amount) { return { minamount: true }; } return null; }; } public static maxAmount(amount: number): ValidatorFn { return (control: FormControl) => { if (control.value && control.value.length > amount) { return { maxamount: true }; } return null; }; } public static compose(validators: ValidatorFn[]): ValidatorFn { return V.compose(validators); } public static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn { return V.composeAsync(validators); } };
这模仿了字符串输入的标准maxLength,minLength和必需的验证,但是修剪和代理标准的其他功能.
要使用它,只需导入验证器而不是@ angular / forms one,例如:
import { FormControl } from '@angular/forms'; import { Validators } from 'path/to/validators'; ... let control = new FormControl('',Validators.compose( Validators.required,Validators.minLength(6) )); ...
这可能不会修剪模型,但它解决了请求中指定的验证问题.