NodeJS

The Importance of Custom Validators and How to Create Them


In Node.js, validation is very important in ensuring that data remains intact and also protected. Even though libraries like express-validator are helpful, it is much easier to implement object-oriented validation with class-validator as it results in more organized, reusable, and clear codes. With class-validator, you can build validation logic in a clean and maintainable way since it works well with TypeScript and plain Javascript. Custom Validators: Their Need and Use

  1. Enhanced Organization: class-validator is a custom validator that uses decorators to apply validation, thereby following a neat object-oriented approach. This makes the code easier to read while simplifying complex validation logic.
  2. Reduced Code Redundancy: Properties and classes can share the same custom validators leading to reduced code duplication and improved maintenance.
  3. Simplified Error Messaging: Users are shielded from complex underlying error messages when custom validators are used.
  4. Enhanced Library Support: Other libraries such as class-transformer work hand in hand with class-validator to ensure that validating and transforming objects is perfected.

How to Create Custom Validators in Node.js with class-validator

1. Install Dependencies

Install class-validator and class-transformer (optional, for object transformation).

npm install class-validator class-transformer

2. Create a Custom Validator

A custom validator is a function that validates the data according to your logic. In order to build a custom validator, you have to use @ValidatorConstraint decorator to specify the rule and @Validate to apply the rule.

Here’s how to build custom email validator which verifies if email domain is:

@mydomain.com:import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments, Validate } from 'class-validator';// Define the custom validator@ValidatorConstraint({ name: 'isEmailDomainValid', async: false })class IsEmailDomainValid implements ValidatorConstraintInterface {  validate(email: string, args: ValidationArguments) {    return email.endsWith('@mydomain.com');  // Check if email ends with '@mydomain.com'  }  defaultMessage(args: ValidationArguments) {    return 'Email must be from the @mydomain.com domain';  }}// Decorator to use on the propertyexport function IsValidEmail() {  return Validate(IsEmailDomainValid);}

 

3. Apply Custom Validator to a DTO (Data Transfer Object)

So, you have now applied the custom validator in a particular class like normally a DTO, which explains what structure the data that needs to be validated should have.

import { IsString, IsEmail, IsInt } from 'class-validator';class UserDTO {  @IsString()  @IsEmail()  @IsValidEmail()  // Applying the custom validator  email: string;  @IsInt()  @Min(18)  age: number;} 

Ready to transform your business with our technology solution? Contact Us today to Leverage Our NodeJS Expertise.

0

NodeJS

Related Center Of Excellence