2016-09-30 269 views
6

在Angular2项目中,我需要验证一些输入。 如何轻松检查输入值是否是整数?Angular 2 Custom Validator:检查输入值是否是一个整数?

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

parseInt(control.value,10)这DIS-认为空间:

如果我有这样的:1米的空间0,24 = 1 ,024则返回1 - 其通过没有错误的验证。

Lodash功能,如:_.isInteger(control.value)_.isNumeric(control.value) // return false every time - 其预期的,因为输入值是一个字符串不是数字。

像这样的组合方法创建了一个凌乱的函数与许多if/else语句,即使如此,我不知道我得到所有的边缘情况。我绝对需要一个更直接的方法。有任何想法吗?

回答

4

这是我迄今为止发现的最彻底的方法:

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 ]); 
} 

验证.service.ts:

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 
     } 
    } 

} 

享受!

+0

它不应该返回类型的文本输入甚至工作{ISNUMERIC :true}如果验证失败? – DSoa

+0

@DSOA也许你是对的。谢谢你纠正我。我的角度技能有点生疏..我现在用榆树..我已经更新了答案.. :) – AIon

+2

'if(condition){return true; } else {return false; ''? :)你是不是指'return(condition);'? –

1

只需创建一个自定义的验证:

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

export function integer(): ValidatorFn { 
    return (control: AbstractControl): ValidationErrors | null => { 
    const error: ValidationErrors = { integer: true }; 

    if (control.value && control.value !== `${parseInt(control.value, 10)}`) { 
     control.setErrors(error); 
     return error; 
    } 

    control.setErrors(null); 
    return null; 
    }; 
} 

然后在表单中使用它:

import { integer } from '...'; 

form.get('yourControl').setValidators([integer()]); 

这将