验证html5输入类型编号

时间:2018-12-11 16:03:27

标签: angular angular-reactive-forms

我想针对以下输入类型显示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。 我该如何区分这两种状态?

1 个答案:

答案 0 :(得分:0)

    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
相关问题