DEV Community

Ushmi Dave
Ushmi Dave

Posted on

6

Custom validation in angular dynamic forms

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.

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 { }

Enter fullscreen mode Exit fullscreen mode

(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

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' }
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

For futher information about dynamic validation refer Dynamic Validation in Angular Dynamic Forms

(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

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);
    }

}

Enter fullscreen mode Exit fullscreen mode

(5) And the final step is the html implementation

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

Enter fullscreen mode Exit fullscreen mode

Custom Validation

Here is the working example

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong Β· web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌢️πŸ”₯

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay