Angular 2 Custom Validator:检查输入值是否为整数? [英] Angular 2 Custom Validator: check if the input value is an integer?

查看:277
本文介绍了Angular 2 Custom Validator:检查输入值是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2项目中,我需要验证一些输入. 如何轻松检查输入值是否为整数?

In an Angular2 project I need to validate some inputs. How to easily check if an input value is an integer?

我尝试使用Number(control.value),它为空字段返回0-不好.

I tried using Number(control.value) which returns 0 for an empty field - not good.

parseInt(control.value,10)不考虑空格:

如果我有类似以下内容:1 space 0,24 = 1 ,024,它将返回1-传递验证器,而不会出现错误.

If i have something like: 1 space 0,24 = 1 ,024 it returns 1 - which passes the validator with no errors.

Lodash函数,例如:_.isInteger(control.value)_.isNumeric(control.value) // return false every time-这是预期的,因为输入值是字符串而不是数字.

Lodash functions like: _.isInteger(control.value) or _.isNumeric(control.value) // return false every time -which is expected, because an input value is a string not a number.

像这样组合方法会创建带有许多if/else语句的杂乱函数,即使这样,我仍不确定我是否能得到所有的边缘情况.我绝对需要更直接的方法.有什么想法吗?

Combining methods like this creates a messy function with many if/else statements, and even then, I'm not sure i get all the edge cases. I definitely need a more straight forward approach. Any ideas?

推荐答案

这是我到目前为止发现的最干净的方法:

This is the cleanest way i found so far:

app.component.html:

<input formControlName="myNumber">

app.component.ts:

export class AppComponent {
    myNumber:FormControl

    constructor(private _ValidatorsService: ValidatorsService){
    }

    this.myNumber= new FormControl('defaultValue',
        [ Validators.required, this._ValidatorsService.isInteger ]);
}

validators.service.ts:

function check_if_is_integer(value){
   // I can have spacespacespace1 - which is 1 and validators pases but
   // spacespacespace doesn't - which is what i wanted.
   // 1space2 doesn't pass - good
   // of course, when saving data you do another parseInt.

   return ((parseFloat(value) == parseInt(value)) && !isNaN(value));

}

@Injectable()
export class ValidatorsService {

   public isInteger = (control:FormControl) => {

        // here, notice we use the ternary operator to return null when value is the integer we want.
        // you are supposed to return null for the validation to pass.

        return check_if_is_integer(control.value) ? null : {
           notNumeric: true
        }
   }

}

享受!

这篇关于Angular 2 Custom Validator:检查输入值是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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