可以使用CustomValidators阻止数据输入文本框吗? [英] Can CustomValidators be used to prevent data entry into textboxes?

查看:76
本文介绍了可以使用CustomValidators阻止数据输入文本框吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将以下代码添加到Angular组件中:

I have added the code below into my Angular component:

NumberValidator(event,element) {
    if (this.onlyNumberKey(event) == false)
      return false;
    if (this.maxLength(event) == false)
      return false;
    else
      return true;

  }

  maxLength(event) {
    var test = event.target.value;
    if (event.target.value.length + 1 > 2)
      return false;
    else
      return true;
  }

  onlyNumberKey(event) {
    let charCode = (event.query) ? event.query : event.keyCode;
    console.log(charCode);
    if (charCode > 31
      && (charCode < 48 || charCode > 57))
      return false;

    return true;
  }

和我的html:

<input type="text" (keypress)="firstNameValidator($event, this)" formControlName="firstName" required>

是否有使用Angular Reactive表单的更优雅的方法,因为对我来说似乎有点不足.我已经研究过CustomValidators,但是,它们只会告诉您是否存在验证错误,即,如果发生验证错误,它们似乎不会阻止数据输入文本框.

Is there a more elegant way to do this using Angular Reactive forms as it seems like a bit of a hack to me. I have looked into CustomValidators, however, they only appear to tell you if there is a validation error or not i.e. they do not appear to stop data entry into text boxes if a validation error occurs.

推荐答案

实现此目标的最佳方法是创建自定义指令.

The best way for you to achieve this would be to make a custom directive.

自定义指令可以使用HostListener侦听您定义的任何事件,例如keyup/keydown.

Custom Directives can listen into any event that you have defined, ex, keyup/keydown using HostListener.

您可以在此指令中定义验证,并在整个文本字段中广泛使用它.

You can define your validation in this directive and use it application wide to the text fields.

这篇关于可以使用CustomValidators阻止数据输入文本框吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆