Naveed Ahmed
Naveed Ahmed

Reputation: 10386

Angular 2 Custom Validator for Reactive Form

Can anyone please guide what is the proper way to implement custom validator for Reactive form if we are not using template driven forms at all?

I have gone through

https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html

and

https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#custom-validation

Both in the end create a directive, is it necessary? or can we do it without creating a directive?

I tried this:

//my-app.module.ts
export interface ValidationResult {
    [key: string]: boolean;
}

function personName(control: FormControl): ValidationResult {

        if (!control.value) {
            return null;
        }

        var valid = /^[a-zA-Z. ]*$/.test(control.value);

        if (valid) {
            return null;
        }
        return { "pattern": true };
    }


@NgModule({
    imports: [
        CommonModule,
        ReactiveFormsModule
    ],
    declarations: [
        MyComponent
    ],
    exports: [
    ],
    providers: [{ provide: NG_VALIDATORS, useExisting: personName, multi: true }]
})
export class MyModule { }

But when I apply personName validator to my reactive form, and test it in browser I get below error in console:

ERROR Error: Uncaught (in promise): Error: No provider for personName!

Upvotes: 2

Views: 1299

Answers (1)

adharris
adharris

Reputation: 3661

When using reactive forms, you don't need to provide your validators. Instead, you attach them to the formControl objects when creating your form in your component. When using the Form Builder, this looks something like:

ngOnInit() {
  this.myform = this.formBuilder.group({
    name: [undefined, personName],
  })
}

Upvotes: 1

Related Questions