skip to Main Content

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


  1. 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 when 123 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.

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

    Updated Plunker

    Login or Signup to reply.
  2. You are using Angular2,
    then you can use html5 form fields. Why do not you use the ‘<input type ="number"/>?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search