gpt4 book ai didi

javascript - Angular 2 : Custom validation for fields with numbers only

转载 作者:太空狗 更新时间:2023-10-29 17:52:54 27 4
gpt4 key购买 nike

我试图在 Angular 2 中进行自定义验证,我已经包含了我所需要的知识,但我无法验证

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 Bootstrap

最佳答案

你正在使用 Angular2,然后你可以使用 html5 表单字段。你为什么不使用'<input type ="number"/>

关于javascript - Angular 2 : Custom validation for fields with numbers only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35636559/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com