yalpsid eman
yalpsid eman

Reputation: 3432

Validate class: Fail validation if field is present

I have an example class (https://github.com/typestack/class-validator#validation-messages). I created a function that should execute a normal validation, or, if specified, execute a validation that fails if the title field is included in the instance being validated.

import {MinLength, MaxLength, validate} from "class-validator";

export class Post {

    @IsString()
    body: strong;

    @IsString()
    title: string;

    public async validatePost(isTitle){
        // if we want the title to be included in the instance, do normal validation
        if(isTitle) {
            validate(this, { forbidUnknownValues: true, validationError: { target: false } });
        }
        // if a title is provided, fail validation
        else {
            // TODO: How can I fail validation if `title` is part of the instance?
        }
    }

}

I know I can have an error thrown when non-whitelisted properties are present (https://github.com/typestack/class-validator#whitelisting), but I can't seem to figure out how to conditionally fail validation if a field is present. Is this even possible without perhaps creating a custom decorator?

Upvotes: 3

Views: 4698

Answers (1)

satanTime
satanTime

Reputation: 13539

There are several options:

you can add a condition: https://github.com/typestack/class-validator#conditional-validation

@ValidateIf(o => o.otherProperty === "value")
@Equals(undefined)
title: string;

if you want it always to be undefined:

@Equals(undefined)
title: string;

If you use class-transformer, you can mark it as @Excluded so whatever value is sent it won't be set to the field.

@Exclude({ toPClassOnly: true })
title: string;

Upvotes: 2

Related Questions