我设法让Formly中的自定义验证器按照此处示例中给出的示例工作:http://angular-formly.com/#/example/advanced/validators
在该示例中,ip地址在formly对象中验证。功能
{
key: 'ip',
type: 'customInput',
validators: {
ipAddress: {
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return /(\d{1,3}\.){3}\d{1,3}/.test(value);
},
message: '$viewValue + " is not a valid IP Address"'
}
},
验证器适用于特定字段。但是如何在其他领域重新使用此验证器?
答案 0 :(得分:1)
您可以将验证器存储在变量中,因为它是简单的对象:
var ipAddressValidator =
{
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return /(\d{1,3}\.){3}\d{1,3}/.test(value);
},
message: '$viewValue + " is not a valid IP Address"'
};
...
{
key: 'ip',
type: 'customInput',
validators: {
ipAddress: ipAddressValidator
},
...
key: 'ip2',
type: 'customInput2',
validators: {
ipAddress: ipAddressValidator
},
...
}
您甚至可以根据某些设置制作生成验证器的工厂。例如:
function getIpValidator (fieldName) {
return {
expression: function(viewValue, modelValue) {
var value = modelValue || viewValue;
return /(\d{1,3}\.){3}\d{1,3}/.test(value);
},
message: '$viewValue + " is not a valid '+fieldName+' Address"'
};
}
...
{
key: 'ip',
type: 'customInput',
validators: {
ipAddress: getIpValidator("Primary IP")
},
...
key: 'ip2',
type: 'customInput2',
validators: {
ipAddress: ipAddressValidator("Secondary IP")
},
...
}