如何将表单域设置为无效?

How can I set a form field as invalid?

我想在删除掩码后验证字段的长度。我正在使用 https://github.com/text-mask/text-mask,因此,我不能只使用 属性 "minLength"。带着不起作用的面具。始终具有预期的大小,即使用户只键入一个字符。因此,需要调用"ngModelChange"中的方法,清除掩码,然后查看文本的长度。

所以问题是,如果我的方法验证失败,如何将此表单字段设置为无效?

checkDigitosCPF() {
  const qtdDigitos = _.replace(this.advogado.cpf, /\D/g, '').length;
  this.isCPFNotOk = _.isEqual(qtdDigitos, 11);
}
<div class="form-group">
  <label class="form-control-label" for="field_cpf">CPF</label>
  <input type="text" class="form-control" name="cpf" id="field_cpf" [(ngModel)]="advogado.cpf" required [textMask]="{mask: cpfMask}" (ngModelChange)="checkDigitosCPF()" minlength="11" />
  <div [hidden]="!(editForm.controls.cpf?.dirty && editForm.controls.cpf?.invalid)">
    <small class="form-text text-danger" [hidden]="!editForm.controls.cpf?.errors?.required" jhiTranslate="entity.validation.required">
      This field is required.
    </small>
    <small class="form-text text-danger" [hidden]="isCPFNotOk">
      Esse campo deve ter no min&iacute;mo 11 car&aacute;cteres.
    </small>
  </div>
</div>

组件中,验证器方法应该如下所示:

// this function should be triggered each time the value change or the form submit

validateField(form): void {
    if (conditionOfError) {
        form.controls.yourFieldName.setErrors({'customLengthError': true})
    } else {
        form.controls.yourFieldName.updateValueAndValidity()
    }
}

形式html错误列表中:

<small *ngIf="yourFieldName?.errors?.customLengthError">
    The error text.
</small>

我解决了这个问题。我通过创建自定义指令获得了所需的行为。