Angular Fromly - 可重复使用的自定义验证器

Angular Fromly - reusable custom validators

我已经设法让 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"'
          }
},

验证器按应有的方式为特定字段工作。但是我如何在其他领域重新使用这个验证器呢?

您可以将验证器存储在一个变量中,因为它是简单的对象:

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")
  },
  ...
}