Home > Net >  Is there a class-validator decorator that rejects strings containing emojis?
Is there a class-validator decorator that rejects strings containing emojis?

Time:07-19

So, i'm building a REST API and I need to verify if there is any emojis in the request body, and if there is I need to throw an expection.

I'm using class-validator lib to do all the verification:

export class CreateShopkeeperDto {
  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  @IsString()
  @MaxLength(64)
  corporateName: string;

  @IsNotEmpty()
  @IsString()
  @MaxLength(64)
  comercialName: string;
}

CodePudding user response:

You need to create a custom validation class

Here's how I think it would go, but this is not tested by me.

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'containsNoEmoji', async: false })
export class ContainsNoEmoji implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    // you probably want a library that has an updated version whenever the unicode specification adds more emoji
    const emojiRegex = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])/gi; // taken from https://dev.to/melvin2016/how-to-check-if-a-string-contains-emojis-in-javascript-31pe
    return !emojiRegex.test(text);
  }

  defaultMessage(args: ValidationArguments) {
    // here you can provide default error message if validation failed
    return 'Text ($value) contains emoji!';
  }
}

Then you would use it like this:

import { ContainsNoEmoji } from "../path/to/ContainsNoEmoji";
import { Validate } from 'class-validator';

export class CreateShopkeeperDto {
  @IsNotEmpty()
  @IsEmail()
  @Validate(ContainsNoEmoji)
  email: string;

  @IsNotEmpty()
  @IsString()
  @MaxLength(64)
  @Validate(ContainsNoEmoji)
  corporateName: string;

  @IsNotEmpty()
  @IsString()
  @MaxLength(64)
  @Validate(ContainsNoEmoji)
  comercialName: string;
}
  • Related