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. 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 the 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.
Contact Us