Custom validation in angular dynamic forms
Tags: rxweb, angular
Published: 2019-09-08 16:31:42

When it comes to validating a reactive dynamic form, it is usually done by using inbuilt validators and setting their properties based upon the respective fields, But complex forms have use cases in which you can be in need to contrivance your custom rules of validation.

So let's create a reactive dynamic form and see how to create custom validation into it.

(1) Install two packages in the project, both package installation command is mentioned below:

> npm install @rxweb/reactive-dynamic-forms

This package is used for building the model-driven dynamic forms.
For more information on reactive dynamic forms, Please refer this article on new way to build angular dynamic forms.

> npm install @rxweb/reactive-form-validators

(2) Now we have to register the `RxReactiveDynamicFormsModule` and `RxReactiveFormsModule` module in the root module.

```js
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { FormsModule,ReactiveFormsModule } from '@angular/forms'; 

import { RxReactiveDynamicFormsModule } from "@rxweb/reactive-dynamic-forms"
import { RxReactiveFormsModule } from "@rxweb/reactive-form-validators"

@NgModule({
  imports:      [ BrowserModule, 
                    FormsModule,ReactiveFormsModule,
                    RxReactiveFormsModule,RxReactiveDynamicFormsModule 
                ],
  declarations: [  ],
  bootstrap:    [  ]
})
export class AppModule { }

```

(3) Now, we have a scenario in which we have a email field in which we want to check whether the email already exists or not, so let's create a model class and define the custom rules into it

```js
import { FormControlConfig } from "@rxweb/reactive-dynamic-forms";
import { AbstractControl } from "@angular/forms"
export class CustomEmailValidation extends FormControlConfig {
 
    validator = (control: AbstractControl) => {
        return control.value != "john@gmail.com" ? null : {
            custom: { message: 'Email already exists' }
        }
    }

}
```

For futher information about dynamic validation refer [Dynamic Validation in Angular Dynamic Forms](https://medium.com/@oojhaajay/dynamic-validation-in-angular-dynamic-forms-aca8df20ece0)

(4) The next step is to create a component and create dynamic form having email control and to apply our custom `CustomEmailValidation`  validation on it, we must specify it in `modelName` 

```js
import { Component, OnInit } from "@angular/core";
import { DynamicFormBuildConfig, DynamicFormConfiguration, RxDynamicFormBuilder } from "@rxweb/reactive-dynamic-forms";
import { CustomEmailValidation } from './custom-validation.model'

@Component({
    selector: 'app-customvalidation-complete',
    templateUrl: './customvalidation-complete.component.html'
})

export class CustomvalidationCompleteComponent implements OnInit {

    serverData: Array<{ [key: string]: any }> = [
        {
            name: "email",
            type: "text",
            modelName:'customEmailValidation',
            ui: {
                label: 'Email'
            }
        }
    ]

    uiBindings: string[] = ["email"];
    
    dynamicFormBuildConfig: DynamicFormBuildConfig;
    
    dynamicFormConfiguration: DynamicFormConfiguration;
    
    constructor(private formBuilder: RxDynamicFormBuilder) { }
    
    ngOnInit() {
        this.dynamicFormConfiguration = {
            controlConfigModels: [{ modelName: 'customEmailValidation', model: CustomEmailValidation }],
          }
        this.dynamicFormBuildConfig = this.formBuilder.formGroup(this.serverData, this.dynamicFormConfiguration);
    }
    
}

```
(5) And the final step is the html implementation

```js
<form [formGroup]="dynamicFormBuildConfig.formGroup">
    <div viewMode="basic" [rxwebDynamicForm]="dynamicFormBuildConfig" [uiBindings]="uiBindings"></div>
</form>

```

![Custom Validation](https://res.cloudinary.com/practicaldev/image/fetch/s--PXrQUsRi--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://thepracticaldev.s3.amazonaws.com/i/332taovucavo7oka6fdu.gif)



Here is the working [example](https://stackblitz.com/edit/angular-maiejv?file=src%2Fapp%2Fcustom-validation.model.ts)