问题描述
根据 thoughtgram.io ,当前支持的验证器为:
According to thoughtgram.io, the currently supported validators are:
- 必填
- 最小长度
- 最大长度
- 模式
因此,请考虑以下代码(在此处插入代码):
So, considering the following code (plunkr here):
@Component({
selector: 'my-app',
template: `
<form #formRef="ngForm">
<input type="number" [(ngModel)]="firstValue" name="firstValue" min="0" required/>
<input type="text" [(ngModel)]="secondValue" maxlength="5" name="secondValue" required/>
<button type="submit"> Submit </button>
</form>
FORM: {{formRef.form | json }}
`
})
export class AppComponent {
firstValue = -22;
secondValue = "eyy macarena!";
}
虽然支持minlength
,但是min="0"
被角度验证忽略:
While minlength
is supported, min="0"
is ignored by angular validation:
因此,当firstValue ngModel<时,使表单导致错误. 0,我需要构建自定义验证器吗?
So, to make the form result in an error when firstValue ngModel < 0, do I need to build a custom validator?
推荐答案
要将min/max validation
应用于number
,您将需要创建Custom Validator
To apply min/max validation
on a number
you will need to create a Custom Validator
Validators 类目前仅有几个验证器,即
Validators class currently only have a few validators, namely
- 必填
- requiredTrue
- 最小长度
- 最大长度
- 模式
- nullValidator
- 撰写
- composeAsync
- required
- requiredTrue
- minlength
- maxlength
- pattern
- nullValidator
- compose
- composeAsync
验证器: 以下是我的数字验证器的简化版本,您可以根据需要对其进行改进
static number(prms = {}): ValidatorFn {
return (control: FormControl): {[key: string]: string} => {
if(isPresent(Validators.required(control))) {
return null;
}
let val: number = control.value;
if(isNaN(val) || /\D/.test(val.toString())) {
return {"number": true};
} else if(!isNaN(prms.min) && !isNaN(prms.max)) {
return val < prms.min || val > prms.max ? {"number": true} : null;
} else if(!isNaN(prms.min)) {
return val < prms.min ? {"number": true} : null;
} else if(!isNaN(prms.max)) {
return val > prms.max ? {"number": true} : null;
} else {
return null;
}
};
}
用法:
// check for valid number
var numberControl = new FormControl("", [Validators.required, CustomValidators.number()])
// check for valid number and min value
var numberControl = new FormControl("", CustomValidators.number({min: 0}))
// check for valid number and max value
var numberControl = new FormControl("", CustomValidators.number({max: 20}))
// check for valid number and value range ie: [0-20]
var numberControl = new FormControl("", CustomValidators.number({min: 0, max: 20}))
这篇关于Angular 2 Final中的最小/最大验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!