2016-09-30 238 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()]); 

這將