0
0
NestJSframework~10 mins

Custom validation decorators in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the necessary decorator for custom validation.

NestJS
import { [1] } from 'class-validator';
Drag options to blanks, or click blank then click option'
AIsString
BValidatorConstraint
CValidate
DIsNotEmpty
Attempts:
3 left
💡 Hint
Common Mistakes
Using decorators meant for property validation like IsString instead of ValidatorConstraint.
2fill in blank
medium

Complete the code to implement the ValidatorConstraintInterface.

NestJS
export class CustomTextLengthValidator implements [1] {
  validate(text: string) {
    return text.length > 5;
  }
}
Drag options to blanks, or click blank then click option'
AValidatorConstraintInterface
BValidationArguments
CValidatorConstraint
DValidationOptions
Attempts:
3 left
💡 Hint
Common Mistakes
Using the decorator name instead of the interface name for implementation.
3fill in blank
hard

Fix the error in the custom decorator function to apply the validation correctly.

NestJS
export function IsCustomText(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    [1](CustomTextLengthValidator, {
      message: 'Text is too short',
      ...validationOptions,
    })(object, propertyName);
  };
}
Drag options to blanks, or click blank then click option'
AIsString
BValidatorConstraint
CValidateIf
DValidate
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class decorator ValidatorConstraint instead of the property decorator Validate.
4fill in blank
hard

Fill both blanks to complete the custom validator class and decorator usage.

NestJS
import { [1], ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'customText', [2]: true })
export class CustomTextLengthValidator implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    return typeof text === 'string' && text.length > 5;
  }
}
Drag options to blanks, or click blank then click option'
AValidatorConstraint
BValidate
Casync
DasyncValidation
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing the async option name or missing the decorator.
5fill in blank
hard

Fill all three blanks to create a custom decorator that uses the validator and accepts validation options.

NestJS
import { Validate, ValidationOptions } from 'class-validator';

export function IsCustomText([1]?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    [2](CustomTextLengthValidator, {
      message: 'Text must be longer than 5 characters',
      ...[3],
    })(object, propertyName);
  };
}
Drag options to blanks, or click blank then click option'
AvalidationOptions
BValidate
DValidatorConstraint
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong decorator or mismatching parameter names.