javascript - 如何以 Angular react 形式执行最小和最大验证?

标签 javascript angular angular2-forms angular-reactive-forms angular-validation

我有以下代码:

    constructor() { 
this.feedbackForm = new FormGroup({
  suggestedAScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required, Validators.maxLength(5), Validators.minLength(5)]),
  minScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required,Validators.minLength(1),Validators.maxLength(1)]),
  maxScore: new FormControl('', [Validators.pattern(/^[0-9]+$/),Validators.required,Validators.minLength(1),Validators.maxLength(1)])
});
this.feedbackForm.setValidators(this.minMaxValidator());
 }




public minMaxValidator() : ValidatorFn{
return (group: FormGroup): ValidationErrors => {
  const min = group.controls['minScore'];
  const max = group.controls['maxScore'];
  var changedValue;
  if (min.value && max.value) {
    if (this.prevMinVal && (this.prevMinVal === min.value)) {
      changedValue = max;
      this.errorMessage = 'Max value should be greater than Min value';
    } else {
      changedValue = min;
      this.errorMessage = 'Min value should be lesser than Max value';
    }
    this.prevMinVal = min.value;
    if (min.value >=  max.value) {
      changedValue.setErrors({notEquivalent: true});
    } else {
      min.setErrors(null);
      max.setErrors(null);
    }
  };
 // this.isFeedbackFormValid();
    return;
 }
 };

使用此代码,当我输入小于最小值的最大值时,错误显示在最小值而不是最大值。我的问题是如何突出显示输入的输入是错误的。任何人都可以建议我提供帮助。谢谢。

最佳答案

您可以像这样创建自定义验证器:

const RangeValidator: ValidatorFn = (fg: FormGroup) => {
  const start = fg.get('min').value;
  const end = fg.get('max').value;
  return start !== null && end !== null && parseFloat(start) < parseFloat(end)
    ? null
    : { range: true };
};

在创建表单时,您必须在 ts 文件中提供完整表单的验证,以便获得输入值更改

this.formbuilder.group({
      min: [null, [//Your Validation for number/decimal]],
      max: [null, [//Your Validation for number/decimal]]
}, { validator: RangeValidator }))

关于javascript - 如何以 Angular react 形式执行最小和最大验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781680/

相关文章:

javascript - 在文件结束前添加和删除文本的正则表达式

javascript - 从 Vision API 文本检测中读取并填充适当的字段

angular - 如何在 Angular 应用程序中使用 powerbi-client 依赖项,而不破坏 Jest 测试?

angular - 从 8 升级到 9 后 ng 构建错误 : Importing unexpected symbol invalidFactory while compiling angular/core

angular - 如何在失去焦点时将输入文本值格式化为 Angular 4 上的货币?

Angular 2 : How to use template reference variables in the new forms from RC2 to display error messages?

javascript - 无法通过 jQuery 访问 AJAX 响应数据

javascript - 使用必须唯一的字段将文档添加到 Firestore

cordova - ionic2 - 屏幕方向

angular - 异步验证器抛出预期的验证器以返回 Promise 或 Observable