typescript 数字和十进制值的 Angular 2 自定义验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44534938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:38:06  来源:igfitidea点击:

Angular 2 custom validation for numbers and decimal values

javascriptangulartypescript

提问by ZAJ

I have a custom validator that checks if an input field has a number entered into it. enter image description here

我有一个自定义验证器,用于检查输入字段中是否输入了数字。 在此处输入图片说明

The code looks like so:

代码如下所示:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class NumberValidators {

  static isNumberCheck(): ValidatorFn {
    return  (c: AbstractControl): {[key: string]: boolean} | null => {
      if (c.value !== undefined && (isNaN(c.value))) {
        return { 'value': true };
      }

      return null;
    };
  }
}

But the issue I have is when I enter a decimal value it is raising the validation flag which I dont want. I want the input field to have whole numbers and decimal numbers. Can somebody please help me get this correct.

但我遇到的问题是,当我输入一个十进制值时,它会引发我不想要的验证标志。我希望输入字段具有整数和十进制数。有人可以帮我解决这个问题吗?

Below is my template code using parsleyjs for validation

下面是我使用 parsleyjs 进行验证的模板代码

<div class="form-group row">
              <label for="upperbeltposition" class="col-md-6 col-form-label">Upper Belt Position (mm) <span class="required">*</span></label>
              <div class="col-md-5">
                <input class="form-control input-transparent " id="upperbeltposition" type="text" formControlName="upperbeltposition"  data-parsley-trigger="blur"
                  required="required" data-parsley-type="number"/>
              </div>
            </div>
             <div class="form-group row">
              <label for="platformxposition" class="col-md-6 col-form-label">Platform X Position (mm) <span class="required">*</span></label>
              <div class="col-md-5">
                <input class="form-control input-transparent " id="platformxposition" type="text" formControlName="platformxposition"  data-parsley-trigger="blur"
                  required="required" data-parsley-type="number"/>
              </div>
            </div>
             <div class="form-group row">
              <label for="platformyposition" class="col-md-6 col-form-label">Platform Y Position (mm) <span class="required">*</span></label>
              <div class="col-md-5">
                <input class="form-control input-transparent " id="platformyposition" type="text" formControlName="platformyposition"  data-parsley-trigger="blur"
                  required="required" data-parsley-type="number"/>
              </div>
            </div>

and in my Component I am using Reactive form and below is my code

在我的组件中,我使用的是 Reactive 表单,下面是我的代码

upperbeltposition: ['', [Validators.required, NumberValidators.isNumberCheck]],
platformxposition: ['', [Validators.required, NumberValidators.isNumberCheck]],
platformyposition: ['', [Validators.required, NumberValidators.isNumberCheck]]

thanks!!

谢谢!!

回答by Teedeez

Something like this should work

这样的事情应该工作

import { AbstractControl, ValidatorFn } from '@angular/forms';

export class NumberValidators {

  static isNumberCheck(): ValidatorFn {
    return  (c: AbstractControl): {[key: string]: boolean} | null => {
      let number = /^[.\d]+$/.test(c.value) ? +c.value : NaN;
      if (number !== number) {
        return { 'value': true };
      }

      return null;
    };
  }
}

回答by Kondal

can use ng-pattern validation

可以使用 ng-pattern 验证

  ng-pattern="^[0-9]+(.[0-9]{0,2})?$"

can you please check once like this

你能像这样检查一次吗

  <label for="upperbeltposition" 
   class="col-md-6 col-form-label" 
   name="number">
     Upper Belt 
     Position (mm)
      <span class="required">*</span>
  </label>
   <div class="col-md-5">
   <input 
    class="form-control input-transparent " 
    id="upperbeltposition" 
    type="text" 
    formControlName="upperbeltposition"  
     data-parsley-trigger="blur"
    required="required" 
    data-parsley-type="number"/> 
    <span  
     ng-show="submitForm && platformxposition 
      .number.$error.pattern">This value should be a valid number
   </span>

  </div>

You must add your form name. and input field name.$error.pattern

您必须添加表单名称。和输入字段名称.$error.pattern

回答by pbre

Instead of creating a custom validator, you can also simply use the Validators.pattern

除了创建自定义验证器,您还可以简单地使用 Validators.pattern

https://angular.io/api/forms/Validators#pattern:

https://angular.io/api/forms/Validators#pattern

['', [Validators.required, Validators.pattern(/^[.\d]+$/)]]

['', [Validators.required, Validators.pattern(/^[.\d]+$/)]]

回答by Herbert

A bit late, but perhaps helpfull for others.

有点晚了,但也许对其他人有帮助。

This regexp will check for validity of decimal value:

此正则表达式将检查十进制值的有效性:

^[-+]?([1-9]{1}\d*|0{1})(\.?)(?(2)\d+)$

The following values / patterns are valid:

以下值/模式有效:

  • 123.7897
  • 12
  • 0.4897
  • +238.345
  • -238.345
  • 123.7897
  • 12
  • 0.4897
  • +238.345
  • -238.345

Values starting with 00 are not valid , so although 00 is technically a number / decimal, functionally it is not.

以 00 开头的值是无效的,所以虽然 00 在技术上是一个数字/十进制,但在功能上它不是。

Use this regexp in a pattern Validator or in your own Validator

在模式验证器或您自己的验证器中使用此正则表达式

Validators.pattern(/^[-+]?([1-9]{1}\d*|0{1})(\.?)(?(2)\d+)$/)