Albert
Albert

Reputation: 2664

Perform a few custom async validations with class-validator

I would like to have the following dto:

export class SetEntryPasswordDto {
    @ApiProperty()
    @Validate(EntryBelongsToUser)
    @Validate(EntryIsNotLocked)
    @Type(() => Number)
    @IsNumber()
    id: number;

    @ApiProperty()
    @IsString()
    @IsNotEmpty()
    @Validate(PasswordMatchValidator)
    @Matches(EValidator.PASSWORD, { message: 'password is not strong enough' })
    password: string;

    @ApiProperty()
    @IsNotEmpty()
    @IsString()
    confirmPassword: string;

    @ApiProperty()
    @IsOptional()
    @IsString()
    passwordHint?: string;

    @IsNumber()
    userId: number;
}

The problem with it is that I need to do a couple of async validations and I would like to use the class-validator lib for this.

My question is: if I do this like in the code snippet above, can I be sure that the first one to complete is EntryIsNotLocked? If not then how to make those validation execute in order?

Thank you.

Additional information:

Seems like there's a bit of information that is of importance.

The EntryBelongsToUser and EntryIsNotLocked are the ValidatorConstraint classes. For instance, one of them looks as follows:

@ValidatorConstraint({ name: 'EntryIsNotLocked', async: false })
@Injectable()
export class EntryIsNotLocked implements ValidatorConstraintInterface {
    constructor(
        private readonly entryService: EntryService,
    ) {}

    public async validate(val: any, args: ValidationArguments): Promise<boolean> {
        // here goes some validation logic
    }

    public defaultMessage(args: ValidationArguments): string {
        return `Unauthorized to execute this action`;
    }
}

The second one looks exactly the same. So the question is can I guarantee the order by setting the async option of the ValidatorConstraint decorator to false for both of them?

Upvotes: 1

Views: 5488

Answers (1)

Kartik Chauhan
Kartik Chauhan

Reputation: 3068

No, you can't be sure of the sequential order of async functions. Thet's why you have validateSync method in class-validator package. You can use the validateSync method instead of the regular validate method to perform a simple non async validation.

See this for reference.

Upvotes: 1

Related Questions