输入类型编号"仅数值"验证

Mih*_*ilo 31 forms validation angular

type="number"如果仅使用Reactive Forms (无指令),如果值为numeric或null,我如何验证输入是否有效?
只有数字[0-9]和.是允许的,没有"e"或任何其他字符.


到目前为止我尝试过的:

模板:

<form [formGroup]="form" novalidate>
    <input type="number" formControlName="number" id="number">
</form>
Run Code Online (Sandbox Code Playgroud)

零件:

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

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

的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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

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

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

Ish*_*awa 34

在HTML文件中,您可以为此添加ngIf模式

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

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

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

  • 要求是该字段可以为空,数字类型,不使用指令,如果它确实不为空,则只允许数字0-9。请提供您的解决方案的工作预览,这个答案确实不是。 (4认同)
  • 很困惑为什么这有这么多赞成票。它没有完全回答这个问题。原始海报使用 &lt;input type="number",它拦截任何非数字输入,留下空控制值,这意味着将显示任何“必需”消息。 (2认同)

lua*_*ped 0

最简单的方法是使用像这样的库特别是你想要noStrings真实的

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

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }
Run Code Online (Sandbox Code Playgroud)

  • 是的,谢谢,但这并没有解决问题的核心。如果输入包含字母“let val = control.value = null”。这是一个问题,当输入值是数字类型时,角度如何解析输入值。如果输入是 **text** 类型,我的验证将完美运行。 (2认同)