输入类型编号“仅数字值"验证 [英] Input type number "only numeric value" validation

查看:80
本文介绍了输入类型编号“仅数字值"验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅使用反应式(无指令)来验证type="number"的输入是否仅是数值或空值?
仅数字[0-9]和.允许,不能使用"e"或任何其他字符.

How can I validate an input of type="number" to only be valid if the value is numeric or null using only Reactive Forms (no directives)?
Only numbers [0-9] and . are allowed, no "e" or any other characters.

到目前为止,我已经尝试过:

<form [formGroup]="form" novalidate>
    <input type="number" formControlName="number" id="number">
</form>

组件:

export class App {
  form: FormGroup = new FormGroup({});

  constructor(
    private fb: FormBuilder,
  ) {
    this.form = fb.group({
      number: ['', [CustomValidator.numeric]]
    })
  }
}

CustomValidator:

export class CustomValidator{
  // Number only validation
  static numeric(control: AbstractControl) {
    let val = control.value;

    if (val === null || val === '') return null;

    if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };

    return null;
  }
}

柱塞

问题是,当用户输入的数字不是数字("123e"或"abc")时,FormControl的值变为null,请记住,我不要该字段是必需的,因此如果该字段确实为空,则null值应该有效.

Plunker

The problem is when a user enters something that is not a number ("123e" or "abc") the FormControl's value becomes null, keep in mind I don't want the field to be required so if the field really is empty null value should be valid.

跨浏览器的支持也很重要(Chrome的数字输入字段不允许用户输入字母-除"e"外,但FireFox和Safari可以输入字母).

Cross browser support is also important (Chrome's number input fields do not allow the user to input letters - except "e", but FireFox and Safari do).

推荐答案

在HTML文件中,您可以为这种样式添加ngIf

In HTML file you can add ngIf for you pattern like this

<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
        <p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
      </div>

在.ts文件中,您可以添加Validators模式-"^ [0-9] * $"

In .ts file you can add the Validators pattern - "^[0-9]*$"

this.Mobile = new FormControl('', [
  Validators.required,
  Validators.pattern("^[0-9]*$"),
  Validators.minLength(8),
]);

这篇关于输入类型编号“仅数字值"验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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