2015-12-22 26 views
0

我已經成功地得到Formly自定義驗證按照在這裏的例子給出的示例工作:http://angular-formly.com/#/example/advanced/validators角Fromly - 可重複使用的自定義驗證

在該示例中,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"' 
      } 
}, 

驗證器適用於特定字段,因爲它應該。但是,我如何在其他領域重新使用這個驗證器?

回答

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