4

我試着做角2定製驗證字段自定義驗證,我已經包括認爲需要在我的知識,但是我無法驗證Angular2:用數字只是

import { FORM_DIRECTIVES, AbstractControl, ControlGroup 
,FormBuilder,Control, Validators } from 'angular2/common'; 
@Component({ 
selector : 'cusValidate', 
template: ` 
<form [ngFormModel] = "myform" (ngSubmit) = "onSubmit()"> 
<lable>Credit Card Number</lable> 
<div> 
<input type = "text" [ngFormControl] = "inputfield"/> 
<div [class.has-error] = '!inval'> 
    </div> 
</div> 
<button type = "submit">Submit</button> 
</form> 
`, 
directives : [FORM_DIRECTIVES] 

}) 
export class cusValidation{ 
myform : ControlGroup; 
inputfield : AbstractControl; 

constructor(fb : FormBuilder){ 
    this.myform = fb.group({ 
     'inputfield' : ['' , Validators.compose([Validators.required 
,this.formValidator])] 
    }) 
    this.inputfield = this.myform.controls['inputfield'] 
} 

formValidator(val : Control) :any { 
    if(val.value.match(/^123/)){ 
     return {inval : true}; 
    } 
} 

onSubmit(){ 
    console.log('submit function called') 
} 
} 
bootstrap(cusValidation); 

也驗證功能在其他文件中我包括但在這裏它在課堂上,即時訪問使用this.function,也如何應用適當的twitter引導

回答

0

我試圖重現它在Plunker和驗證稱爲罰款。

我不確定你的期望。目前formValidator表示輸入123時發生錯誤,其他所有內容均被視爲有效('ab','12','xyz123')。

如果要指示錯誤返回帶有錯誤鍵和任意值的對象(例如錯誤消息)。

如果你想表明沒有錯誤(值是有效的),然後返回null

formValidator(val : Control) :any { 
    if(val.value.match(/.*[^0-9].*/)){ 
     return {inval : true}; 
    } 
} 

更新Plunker

+0

我希望只要用戶不要輸入唯一的數字輸入字段改變其顏色,以指示錯誤,並顯示msg「數字是隻允許」 – blackHawk

+0

是不夠的返回,返回{inval:true};從裏面的功能 – blackHawk

+0

確定它夠了。我只是懷疑目前它並沒有返回你想要的狀況,但你沒有提供足夠的信息讓我知道你實際上想要完成什麼。 –

4

您使用Angular2, 那麼你可以使用HTML5的表單字段。你爲什麼不使用'<input type ="number"/>

+0

它仍然會允許在該輸入字段上的'e'(指數)字符..這再次沒有意義。 –