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

标签 html css angular typescript angular5

我想在移除掩码后验证字段的长度。我正在使用 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()
    }
}

form html错误列表中:

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

关于html - 如何将表单域设置为无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507939/

相关文章:

jquery - 单击时更改选择选项的背景颜色

angular - 有没有办法避免在 Ionic 3 中的列表更新后 View 闪烁?

angular - 如何在 Angular 7 中从 ckeditor 5 检索数据?

javascript - 相对改变div大小的全部内容

html - 聊天页面的 CSS : 1 column for users list and 1 column for the chat

html - CSS Flexbox - 正确对齐单元格列

html - 突出显示所选行突出显示所有行

javascript - 如何在javascript中访问单击表格行的特定单元格

jquery - 为什么不能在 jquery .animate() 中使用 $(this)?

jquery masonry 在初始页面加载时崩溃,单击 "home"菜单按钮后工作正常