npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-reactive-form-class-validator

v1.8.2

Published

A lightweight library for dynamically validate Angular reactive forms using class-validator library.

Downloads

192

Readme

ngx-reactive-form-class-validator

A lightweight library for dynamically validate Angular reactive forms using class-validator library.

Table of contents

Installation

npm install --save ngx-reactive-form-class-validator

// OR

yarn add ngx-reactive-form-class-validator

Peer dependencies

"@angular/common": ">= 2.0.0 <= ^18.0.0",
"@angular/core": ">= 2.0.0 <= ^18.0.0",
"@angular/forms": ">= 2.0.0 <= ^18.0.0",
"class-validator": ">= 0.12.0 <= ^0.14.0"
While this library will function with any version of class-validator within this range, we strongly recommend using class-validator ^0.14.0 or later due to a critical security vulnerability addressed in versions 0.14.0 and beyond. This ensures the highest level of security for your application.

Usage

Defining classes with validators and deserializers

Please note that properties without a class-validator decorator will not be validated, see class-validator profile.ts

import { IsEmail, IsNotEmpty, ValidateNested } from 'class-validator';  
  
class Profile {  
  @IsNotEmpty()  
  public firstName: string;  
  
  @IsNotEmpty()  
  public lastName: string;  

  @IsEmail()  
  public email: string;  	
  
  @ValidateNested()  
  public address: Address;  
}

address.ts

import { IsNotEmpty, IsOptional, ValidateNested } from 'class-validator';  

class Address {  
  @IsNotEmpty()  
  public street: string;  
  
  @IsNotEmpty()  
  public city: string;  
  
  @IsOptional()  
  public state: string;  
  
  @IsNotEmpty()  
  public zip: string;  
} 

Untyped classes

Untyped version of ngx-class-validator form classes exist in order to be backward compatible with angular untyped form classes

Creating a ClassValidatorFormGroup

Using ClassValidatorFormBuilderService

As described here to be able to use the ClassValidatorFormBuilderService, you need to import ClassValidatorFormBuilderModule.

app.module.ts

imports: [  
  ...
  ClassValidatorFormBuilderModule.forRoot(),  
  ...
],

Then in your component profile-form.component.ts

public constructor(  
 private fb: ClassValidatorFormBuilderService,  
) { }

 profileForm =  this.fb.group(Profile,
    {
     firstName:  [''],
     lastName:  [''],
     email: [''],
     address: this.fb.group(Address,
	      {
		      street:  [''],
		      city:  [''],
		      state:  [''],
		      zip:  ['']
		  }
	  ),
    });

Using ClassValidatorFormGroup class

As it's possible with angular FormGroup class we can directly create a ClassValidatorFormGroup using the constructor

export class ProfileFormComponent {
  profileForm = new ClassValidatorFormGroup({
    firstName: new ClassValidatorFormControl(''),
    lastName: new ClassValidatorFormControl(''),
  });
}

Now, setting value to any of form controls, will perfom the validator set in the corresponding class.

this.profileForm.controls.email.setValue('notEmailValue');
console.log(this.profileForm.controls.email) // { isEmail: 'email must be an email' }

this.profileForm.controls.email.setValue('[email protected]');
console.log(this.profileForm.controls.email) // null

Add custom validators

It is possible as well to combine dynamic validation with custom validation. There are several ways to do it:

Providing validators when creating the ClassValidatorFormControl

this.fb.group (Profile, {  
      email: ['', Validators.required],
      ...
  }
)

// OR

new ClassValidatorFormGroup(Profile, {
	email: new ClassValidatorFormControl('', Validators.required)
})

Providing validators using setValidators/setValidatorsWithDynamicValidation methods

Both setValidators and setValidatorsWithDynamicValidation replace validators provided in parameter, the only one difference is that setValidatorsWithDynamicValidation add given validators as well as re-enable dynamic validation, as the setValidators method replace validators with given ones without re-enabling dynamic validation.

emailControl.setValidators(Validators.required); // there will be only Validators.required validator

emailControl.setValidatorsWithDynamicValidation(Validators.required) // there will be Validaros.required validator as well as dynamic validator

Available classes

ClassValidatorFormBuilderModule

An Angular module that provides ClassValidatorFormBuilderService for dependency injection. It can either be imported forRoot or normally (We don't recommend importing it normally because that will create multiple instances of ClassValidatorFormBuilderService).

app.module.ts

imports: [  
  ...
  ClassValidatorFormBuilderModule.forRoot(),  
  ...
],

ClassValidatorFormBuilderService

An Angular injectable service having the same methods as Angular FormBuilder except a minor change of group method signature, see below:

group(  
  classType: ClassType<any>, // The class type of the form group value.
  // Angular FormBuilder group method parameters
  controlsConfig: { [p: string]: any },  
  options?: AbstractControlOptions | { [p: string]: any } | null,  
): ClassValidatorFormGroup;

classType parameter

We've introduced a new parameter called classType (a class type containing class-validator decorators) that you should provide, to enable us to perform dynamic validations.

ClassValidatorFormGroup

A typescript class extending angular FormGroup class, with a minor change of constructor signature, the classType parameter.

export class ClassValidatorFormGroup extends FormGroup {        
 public constructor(  
      private readonly classType: ClassType<any>, 
      // Angular FormGroup constructor parameters
      controls: {  
          [key: string]: AbstractControl;  
      },  
      validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,  
      asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,  
  ) {  
    ... 
  }

ClassValidatorFormControl

A typescript class extending angular FormControl class, that will use the classType instance to perform validations and assign validation errors to the ClassValidatorFormControl.

As it extends angular FormControl class, it contains all FormControl methods, with a custom new method:

setValidatorsWithDynamicValidation(newValidator: ValidatorFn | ValidatorFn[] | AbstractControlOptions | undefined): void

This method has the same signature as FormControl setValidators method. In addition it re-enables dynamic validation when disabled.

Developer note

We are open for proposals, so please don't hesitate to create issues if you want to report any bugs/proposals/feature requests.