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:

  1. <input formControlName="myNumber">

app.component.ts:

  1. export class AppComponent {
  2. myNumber:FormControl
  3.  
  4. constructor(private _ValidatoRSService: ValidatoRSService){
  5. }
  6.  
  7. this.myNumber= new FormControl('defaultValue',[ Validators.required,this._ValidatoRSService.isInteger ]);
  8. }

validators.service.ts:

  1. function check_if_is_integer(value){
  2. if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
  3. // I can have spacespacespace1 - which is 1 and validators pases but
  4. // spacespacespace doesn't - which is what i wanted.
  5. // 1space2 doesn't pass - good
  6. // of course,when saving data you do another parseInt.
  7. return true;
  8. } else {
  9. return false;
  10. }
  11. }
  12.  
  13. @Injectable()
  14. export class ValidatoRSService {
  15.  
  16. public isInteger = (control:FormControl) => {
  17. return check_if_is_integer(control.value) ? null : {
  18. notNumeric: true
  19. }
  20. }
  21.  
  22. }

请享用!

猜你在找的JavaScript相关文章