如何在2输入中创建自定义表单验证器?我想验证一个输入数字始终大于另一个

时间:2018-09-20 14:15:30

标签: angular comparison angular-reactive-forms reactive

如何在2个输入中创建自定义表单验证器?我想验证一个输入数字始终大于另一个输入数字。

  ValidateMaxMin(control: FormControl) {
    console.log(control.value.productMin);
    if (control.value.productMin != 0) {
      return { hasError: true };
    }
    return null;
  }



 this.productForm = this.fb.group ({ //form validator for create and update
      '_id': [ "" ],
      'productName': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Z\s]*$/), Validators.minLength(1), Validators.maxLength(50)]) ],
      'supplierId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'brandId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'categoryId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'productPrice': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productQuantity': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productMax': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productMin': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(0), Validators.max(99999), this.ValidateMaxMin ]) ],

    });

在上面的代码中,我只能验证一个特定字段,而我的意图是指定/获取两个字段并进行比较。

1 个答案:

答案 0 :(得分:0)

这是验证方法,可以完成您想要的

static ValidateMaxMin(firstField: FormControl | AbstractControl | null,
                      secondField: FormControl | AbstractControl | null,
                      message = `one input number should alwasy be greater than another`
): ValidatorFn {
return (): ValidationErrors | null => {
  if (firstField && secondField && firstField.value >= secondField.value) {
    const notGreater = { notGreater: { message: message } };
    secondField.setErrors(notGreater);
    return notGreater;
  }
  notGreater!.setErrors(null);
  return null;
};

}

以及如何在表单中使用它的示例

this.form = this.fb.group({
  firstField: ['', Validators.required],
  secondField: ['', Validators.required],
});
this.form.setValidators(Validators.passwordConfirming(this.form.get('password'), this.form.get('passwordConfirm')));