typescript 对象成员上的Angular验证器(以React形式)

pgvzfuti  于 2023-05-01  发布在  TypeScript
关注(0)|答案(2)|浏览(175)

Angular Reactive Formbuilder

this.formBuilderGroup({
  'productType':['',[Validators.required, Validators.min(3)]],
  'deliveryCategory':['',[Validators.required, Validators.max(8)]]
})

它们实际上是从“材质”选择下拉列表中驱动的,并为对象给予Dto。如何在实际的Object成员上设置验证器?
例如productType。productTypeId验证程序最小值为1。
和deliveryCategory。deliveryCategoryNo min % 1?
Validators.min当前仅在整个对象上。
如何编写自定义的验证程序,将对象作为对象成员作为参数?还是有更好的办法?

cwdobuhd

cwdobuhd1#

这需要一个自定义的验证器,可以这样写:

// pass in property to validate and list of validators to run on it
export function validateProperty(property: string, validators: ValidatorFn[]): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    // get the value and assign it to a new form control
    const propertyVal = control.value && control.value[property];
    const newFc = new FormControl(propertyVal);
    // run the validators on the new control and keep the ones that fail
    const failedValidators = validators.map(v => v(newFc)).filter(v => !!v);
    // if any fail, return the list of failures, else valid
    return failedValidators.length ? {invalidProperty: failedValidators} : null;
  };
}

使用方法:

'productType':['', validateProperty('propertyToValidate', [Validators.required, Validators.min(3)])],
llycmphe

llycmphe2#

被接受的解决方案的函数签名应该是。.

validateProperty(property: string, validators: ValidatorFn[]): ValidatorFn

相关问题