Im trying to do custom validation in angular 2, I have included what needed in my knowledge but Im unable to validate
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);
also validator function was in other file that i included but here its in class and im accessing using this.function, also how to apply appropriate twitter bootstrap
2
Answers
I tried to reproduce it in this Plunker and validation is called fine.
I’m not sure what you expect. Currently the
formValidator
indicates an error when123
is entered, everything else is considered valid (‘ab’, ’12’, ‘xyz123’).If you want to indicate an error return an object with error key and an arbitrary value (for example error message).
If you want to indicate no error (value is valid) then return
null
.Updated Plunker
You are using Angular2,
then you can use html5 form fields. Why do not you use the ‘
<input type ="number"/>
?