#custom validator decorator breaking chain

4 messages · Page 1 of 1 (latest)

frosty zinc
#

I have a custom validator, which works as expected, except the decorator is breaking the other validators from running. I'm not sure what I'm doing wrong. See code in the thread.

#
@CheckVehicleExists()
@IsObject()
@IsNotEmpty({ message: 'required' })
@ValidateNested({ each: true })
@Type(() => CreateNewAccountVehicleDto)
vehicle: CreateNewAccountVehicleDto
#

The @CheckVehicleExists() is the offending validation that is preventing all others from running.

#

This is the file for the validation decorator

/* eslint-disable @typescript-eslint/no-unused-vars */
import { forwardRef, Inject, Injectable } from '@nestjs/common'
import {
    registerDecorator,
    ValidationArguments,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface
} from 'class-validator'
import { VehiclesService } from '../../vehicles/vehicles.service'

export function CheckVehicleExists(validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            validator: CheckVehicleExistsConstraint
        })
    }
}

@ValidatorConstraint({ name: 'CheckVehicleExists', async: true })
@Injectable()
export class CheckVehicleExistsConstraint
    implements ValidatorConstraintInterface
{
    constructor(
        @Inject(forwardRef(() => VehiclesService))
        private readonly vehiclesService: VehiclesService
    ) {}

    async validate(value: any, args: ValidationArguments) {
        value.plateTypeId = value.plateTypeId ?? 0
        const { plateNumber, plateState, plateTypeId } = value
        const exists = await this.vehiclesService.checkExists({
            plateNumber,
            plateState,
            plateTypeId
        })

        return !exists
    }

    defaultMessage(args: ValidationArguments) {
        return `Vehicle already exists on an account`
    }
}