创建类以在 angular 4 中保存所有自定义验证的正确方法

Hac*_*ker 2 custom-validators angular angular-reactive-forms angular4-forms

我创建了一个类,其中包含我的应用程序的所有自定义验证。只是想知道这是否是正确的方法。我在网上看到了一些例子并想出了这段代码。每个方法都必须是静态的吗?如果我删除静态密钥工作,我会收到编译错误。

import { FormControl, ValidatorFn } from '@angular/forms';

export class FormValidator {

     static validategreater(maxVal, minVal): ValidatorFn {
    return (control: FormControl) => {
      if (control.dirty) {

          if (enteredValue > maxVal) {
            returnObj['greaterError'] = true;
          }
       if (Object.keys(returnObj).length > 0) {
          return returnObj;
        }
      }
      return null;
    };
  }

}
Run Code Online (Sandbox Code Playgroud)

len*_*ndc 5

如何存储自定义验证器没有标准,它只需要是一个实现ValidatorFn合约的函数。但是建议您遵循angular-forms' 标准,因为开发人员已经习惯了它,这样您的代码更容易理解。

您可以使用静态成员(如您所建议的)存储在类上:

class MyCustomValidators {
    // it has to be called like MyCustomValidators.withParams(123, 456)
    static withParams(param1, param2) : ValidatorFn {
       return (control: FormControl) => { /*implementation*/ }
    }

    // it has to be called like MyCustomValidators.withoutParams1
    static withoutParams1(control: FormControl) {
       /*implementation*/
    }

    // it has to be called like MyCustomValidators.withoutParams2()
    static withoutParams2() : ValidatorFn {
       return (control: FormControl) => { /*implementation*/ }
    }
}
Run Code Online (Sandbox Code Playgroud)

functions仅:

export const MyCustomValidator = (control: FormControl) => { /*implementation*/ }

export const MyCustomValidator2 = (param1) => (control: FormControl) => {
    /*implementation*/
}
Run Code Online (Sandbox Code Playgroud)

如您所见,重要的部分是(control: FormControl) => { /*implementation*/ }函数;因此,ValidatorFn只要打字稿允许,您就可以以多种方式存储您的内容。

此外,有时当它是基于其良好的背景下,组织验证,例如CommonValidatorsCustomerValidatorsProductValidators等,这有助于你保持聚合验证器类的责任更加清晰,也不要混用有更具体的验证例如,通用验证器使代码维护更容易。

总之,您可以选择要存储自定义验证的任何标准;虽然,使用静态方法的类更好,因为它保持相同的标准angular-forms用途,因此使用验证器更直观,因为它是众所周知的标准。

如果我删除静态密钥工作,我会收到编译错误。

如果删除静态,则必须创建类的实例才能访问验证器成员。

new FormValidator().validategreater(1,2)
Run Code Online (Sandbox Code Playgroud)