带有参数的Angular 2自定义验证器 [英] Angular 2 custom validator with parameters
问题描述
如何在Angular 2中创建我自己的maxLength验证器? 我可以找到的所有示例都使用类似于必需"的验证器,这意味着他们已经知道规则.他们只接受一个参数-控件本身.如何传递更多参数?
How do I create let's say my own maxLength validator in Angular 2? All examples I could find use validators similar to 'required' one meaning that they already know the rules. They only accept one param - the control itself. How do I pass more parameters?
这是我的示例验证器.如何修改它以将数字5传递为参数?
Here's the sample validator I have. How do I modify it to pass number 5 as a parameter?
export class MyValidators {
static minValue(control:Control): {[s: string]: boolean} {
var num = +control.value;
if (isNaN(num) || num < 5 ) { return {"minValue": true}; }
return null;
}
}
推荐答案
这里是一个示例.这是一个最小值验证器,您可以在其中传递一个数字进行验证.
Here is a sample. It's a min value validator where you pass in a number to validate.
import {Control} from 'angular2/common';
export const minValueValidator = (min:number) => {
return (control:Control) => {
var num = +control.value;
if(isNaN(num) || num < min){
return {
minValue: {valid: false}
};
}
return null;
};
};
更多详细信息可以在自定义验证程序官方文档页面中找到.
More details can be found in the Custom Validators official documentation page.
这篇关于带有参数的Angular 2自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!