0
0
NestJSframework~20 mins

Custom validation decorators in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when validating a DTO with this custom decorator?
Given this NestJS custom validation decorator and DTO, what will be the validation result if the input value is 'abc123'?
NestJS
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ async: false })
export class IsAlphaOnlyConstraint implements ValidatorConstraintInterface {
  validate(text: string, args: ValidationArguments) {
    return /^[A-Za-z]+$/.test(text);
  }
  defaultMessage(args: ValidationArguments) {
    return 'Text ($value) must contain only letters';
  }
}

export function IsAlphaOnly(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsAlphaOnlyConstraint,
    });
  };
}

class SampleDto {
  @IsAlphaOnly({ message: 'Only letters allowed!' })
  name: string;
}

// Input: { name: 'abc123' }
AValidation throws a runtime error
BValidation passes successfully
CValidation fails with message: 'Text (abc123) must contain only letters'
DValidation fails with message: 'Only letters allowed!'
Attempts:
2 left
💡 Hint
Think about what the regex /^[A-Za-z]+$/ checks for and what input 'abc123' contains.
📝 Syntax
intermediate
2:00remaining
Which option correctly registers a custom validator in NestJS?
You want to create a custom validation decorator using class-validator in NestJS. Which of the following code snippets correctly registers the validator?
AregisterDecorator({ target: object.constructor, propertyName, validator: MyValidator, options: validationOptions });
BregisterDecorator({ target: object.constructor, propertyName, validator: new MyValidator(), options: validationOptions });
CregisterDecorator({ target: object.constructor, propertyName, validator: MyValidator });
DregisterDecorator({ target: object, propertyName, validator: MyValidator, options: validationOptions });
Attempts:
2 left
💡 Hint
Remember the target should be the constructor of the object, not the object instance itself.
🔧 Debug
advanced
2:00remaining
Why does this custom validator always pass validation?
Consider this custom validator code in NestJS. Why does it always pass validation regardless of input?
NestJS
import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

@ValidatorConstraint({ async: false })
export class AlwaysTrueValidator implements ValidatorConstraintInterface {
  validate(value: any) {
    return true;
  }
  defaultMessage() {
    return 'This should never fail';
  }
}

// Used in a decorator but validation never fails
AThe validator class is not decorated with @Injectable().
BThe validate method always returns true, so validation never fails.
CThe defaultMessage method is not called.
DThe decorator is missing the registerDecorator call.
Attempts:
2 left
💡 Hint
Look at the return value of the validate method.
state_output
advanced
2:00remaining
What is the validation error message for this input?
Given this custom validator and DTO, what error message will be shown if the input is { age: 17 }?
NestJS
import { registerDecorator, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ async: false })
export class IsAdultConstraint implements ValidatorConstraintInterface {
  validate(age: number, args: ValidationArguments) {
    return age >= 18;
  }
  defaultMessage(args: ValidationArguments) {
    return `Age must be at least 18, but got ${args.value}`;
  }
}

export function IsAdult(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsAdultConstraint,
    });
  };
}

class UserDto {
  @IsAdult({ message: 'User must be adult!' })
  age: number;
}

// Input: { age: 17 }
AValidation fails with message: 'User must be adult!'
BValidation passes successfully
CValidation fails with message: 'Age must be at least 18, but got 17'
DValidation throws a runtime error
Attempts:
2 left
💡 Hint
Check which message is prioritized when both defaultMessage and options.message exist.
🧠 Conceptual
expert
2:00remaining
Which statement about custom validation decorators in NestJS is TRUE?
Select the correct statement about creating and using custom validation decorators with class-validator in NestJS.
AThe defaultMessage method is required and must return a string synchronously.
BCustom validators must always be asynchronous and return a Promise<boolean>.
CThe validate method can be synchronous or asynchronous, but the decorator must specify async: true if asynchronous.
DCustom decorators cannot use constructor injection for dependencies.
Attempts:
2 left
💡 Hint
Think about how async validation is handled in class-validator.