javascript – Angular 2 Custom Validator:检查输入值是否为整数?

前端之家收集整理的这篇文章主要介绍了javascript – Angular 2 Custom Validator:检查输入值是否为整数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular2项目中,我需要验证一些输入.
如何轻松检查输入值是否为整数?

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

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

如果我有类似的东西:1 space 0,24 = 1,024它返回1 – 它通过验证器没有错误.

Lodash的功能如下:_.isInteger(control.value)或_.isNumeric(control.value)
//每次返回false – 这是预期的,因为输入值是字符串而不是数字.

组合这样的方法会产生一个带有许多if / else语句的混乱函数,即便如此,我也不确定我是否得到了所有边缘情况.我当然需要更直接的方法.有任何想法吗?

解决方法

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

app.component.html:

@H_403_20@<input formControlName="myNumber">

app.component.ts:

@H_403_20@export class AppComponent { myNumber:FormControl constructor(private _ValidatoRSService: ValidatoRSService){ } this.myNumber= new FormControl('defaultValue',[ Validators.required,this._ValidatoRSService.isInteger ]); }

validators.service.ts:

@H_403_20@function check_if_is_integer(value){ if((parseFloat(value) == parseInt(value)) && !isNaN(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 true; } else { return false; } } @Injectable() export class ValidatoRSService { public isInteger = (control:FormControl) => { return check_if_is_integer(control.value) ? null : { notNumeric: true } } }

请享用!

猜你在找的JavaScript相关文章