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

Right way of creating a class to hold all the custom validations in angular 4

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

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;
    };
  }

}

我们也走上了同样的道路。 angular 团队也采用了类似的方式。 在这里查看他们的代码: https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts

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

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

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*/ }
    }
}

或仅functions

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

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

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

此外,有些情况下根据上下文组织验证器是很好的,例如 CommonValidatorsCustomerValidatorsProductValidators 等。这有助于您保持聚合验证器的责任 class 更加明确,也不要将更具体的验证器与通用验证器混合使用,例如使代码维护更容易。

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

If i remove the static key work, i get compilation errors.

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

new FormValidator().validategreater(1,2)