【问题标题】:Validation for html5 input type number验证 html5 输入类型号
【发布时间】:2018-12-11 16:03:27
【问题描述】:

我想为以下输入类型显示 2 条不同的验证消息

<input type="number" step="1" formControlName="Ordinal" />

我正在使用具有与此类似的 formGroup 的反应式表单

formBuilder.group({
  ..
  Ordinal: [0, [Validators.required, CustomValidators.integer]],
  ..
});

如果根本没有输入,一个验证器Validators.required 应该显示一条必需的消息。如果输入了无效号码,另一个验证器Validator.integer 应该会显示一条消息。

Validation.integer 的当前实现如下所示

export function integer(control: FormControl) {
  const value = control.value;
  if ((parseFloat(value) === parseInt(value, 10)) && !isNaN(value) || value === '' || value === null) {
    return null;
  } else {
    return {
      notNumeric: true
    };
  }
}

我的问题是type="number" 浏览器在两种情况下都会返回null(输入为空/数字无效时)。 如何区分这两种状态?

【问题讨论】:

  • 你为什么要这个条件? (parseFloat(value) === parseInt(value, 10)
  • 只是检查它是否是整数。但是很好的问题,为什么我不只使用 Number.isInteger()。老实说我不记得了,我第一次写这篇文章是很久以前的事了

标签: angular angular-reactive-forms


【解决方案1】:
    to check numeric value I thinks `isNaN and  Number.isInteger()` would be enough 

    Please check the following updated conditions :-


    export function integer(control: FormControl) {
      const value = control.value;
      if(value === 'null' || value === undefined || value === '' ){
       return isRequired: true
      }
     else if ((!Number.isInteger(value) || !isNaN(value))) {
        return null;
      } else {`enter code here`
        return {
          notNumeric: true
        };
      }
    }


    hope this helps

【讨论】:

  • 谢谢,我会检查的。但这并不能解决我的主要问题,即我无法区分这两种情况(无输入 -> 需要验证和错误输入 -> 整数验证)。我需要两个不同的验证消息,为此我需要两个不同的验证器(或至少两个不同的返回值)。由于两个状态都返回 null,我无法单独检查它们。
  • 我已经更新了我的答案,请检查。现在您还可以检查所需条件
  • 这不起作用,因为如果输入无效,则值为null。所以我会得到isRequired 而不是notNumeric
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 2017-12-16
  • 2015-07-30
  • 2013-05-18
相关资源
最近更新 更多