繁体   English   中英

如何在Angular中的模板中获取表单控件验证错误

[英]How to get form control validation errors in template in Angular

我有一个表格,可以根据下拉菜单中的某些值更改其验证。 如果选择了大学A,则必须在60中选择最小百分比,如果选择了大学B,则最小百分比将降至55。尽管我已经找到了一种获取模板中最小误差的方法,所以我不必费劲在模板中编写百分比值。 尽管我不确定这是否是正确的方法。

<div formGroupName="marks">
  <div class="form-group">
    <label for="email" class="col-lg-3 control-label">Semester 1</label>
    <div class="col-lg-3">
      <input autocomplete="off"
             #sem1
             type="text"
             min="0"
             max="99"
             maxlength="1"
             maxlength="2"
             class="form-control"
             id="email"
             placeholder="Sem 1 (%)"
             (keypress)="onlyNumberKey($event)"
             formControlName="sem1">
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Sem 1 percentage required
      </span>
      <span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
                   registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
                   registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
                   registrationForm.controls['marks'].controls['sem1'].touched"
                   class="text-danger">
        Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
      </span>
    </div>
  </div>
</div>

零件

registrationForm = new FormGroup({
  college: new FormControl('', [
    Validators.required, dropDrownValidator
  ]),
  marks: new FormGroup({
    sem1: new FormControl('',
      [
        Validators.required,
        Validators.min(60),
        Validators.max(99),
        Validators.minLength(1),
        Validators.maxLength(2)
      ]
    )
  })
});

嗯,值得一提的是,由于此问题minmax内置验证器已在4.3.0-beta.0中回滚,并且不再(可能)在4.3.0 final中导出。 大概他们应该回到v5了。

话虽如此,我建议您或者自己做一个自定义验证器,或者将min 验证器从源代码( @angular/forms )复制到您的项目中,以防止将来发生中断。

这是修改后的复制粘贴版本:

function customMin(min: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value == null || min == null) {
      return null;
    }

    const value = parseFloat(control.value);

    return isNaN(value) || value >= min ? null : {
      customMin: { min, actual: control.value }
    };
  };
}

为了实现您想要的目标,您必须注意 college 控制方面的变化。

您可以使用模板中的 (change)来执行此操作:

<select formControlName="college" (change)="myAwesomeFunction($event.target.value)">
  ...
</select>

甚至在component中使用valueChanges

this.registrationForm.get('college').valueChanges.subscribe(college => this.myAwesomeFunction(college));

function ,根据大学用户的选择,您可以使用AbstractControl#setValidators将最小值设置为验证器,如下所示:

myAwesomeFunction() {
  const min: number = college === 'CollegeA' ? 60 : 55;
  const control: FormControl = this.registrationForm.get('marks.sem1');

  control.setValidators([Validators.required, customMin(min)]);
  control.updateValueAndValidity();
}

提示:

1-由于您使用的是模型驱动的表单,因此您不应该在HTML中进行验证,保持其整洁并将所有内容都放入组件中。

2-您可以使用FormBuilder来简化form的构造(请参见下面的PLUNKER)。

3-绝对不要这样访问私有属性:

{{ registrationForm.get('marks.sem1')._errors.min.min

如果需要,只需使用errors而不是_errors即可。

4-您可以简化标记:

代替:

<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
             registrationForm.controls['marks'].controls['sem1'].touched" 
             class="text-danger">
  Sem 1 percentage required
</span>
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
             registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
             registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
             registrationForm.controls['marks'].controls['sem1'].touched"
             class="text-danger">
  Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }}  and above.
</span>

你可以有:

<div class="text-danger" *ngIf="registrationForm.get('marks.sem1').touched">
  <span *ngIf="registrationForm.hasError('required', 'marks.sem1')">
    Sem 1 percentage required
  </span>
  <span *ngIf="registrationForm.getError('customMin', 'marks.sem1') as error">
    Percentage must be greater than or equal to {{ error.min }}.
  </span>
</div>

工作演示(使用自定义验证器)


PS:如果您不关心将来的发行版中的中断,但仍想使用Validators.min ,则只需更改以下行即可:

control.setValidators([Validators.required, customMin(min)]);

对此:

control.setValidators([Validators.required, Validators.min(min)]);

工作演示(使用内置验证器)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM