代码之家  ›  专栏  ›  技术社区  ›  Hacker

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

  •  0
  • Hacker  · 技术社区  · 6 年前

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

    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;
        };
      }
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   lenilsondc    6 年前

    对于如何存储自定义验证器没有标准,它只需要是一个实现 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*/ }
        }
    }
    

    functions 仅限:

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

    如你所见,最重要的是 (control: FormControl) => { /*implementation*/ } 因此,您可以存储

    此外,在有些情况下,根据上下文组织验证器是很好的,例如, CommonValidators , CustomerValidators , ProductValidators 等等。这有助于您更清楚地承担聚合验证器类的责任,也不必将更具体的验证器与常规验证器混合使用,例如使代码维护更容易。

    总之,您可以选择要存储自定义验证的任何标准;不过,使用带有静态方法的类更好,因为它保持了相同的标准 角形 使用,因此使用验证器更加直观,因为它是一个众所周知的标准。

    如果删除静态密钥工作,就会出现编译错误。

    new FormValidator().validategreater(1,2)
    
        2
  •  0
  •   Aniket Kadam    6 年前

    我们也走了同样的路。 角度小组也以类似的方式来做。 在这里查看他们的代码: https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts