Search code examples
typescriptclass-validator

Validating one field in a class with class-validator


Let's say I have this class based on the example in the docs (https://github.com/typestack/class-validator#usage)

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

export class Post {

    @IsString()
    body: strong;

    @IsString()
    title: string;

    //...many more fields

    public async validate(){
        validate(this, { forbidUnknownValues: true, validationError: { target: false } });
    }
}

I create an instance of this class and assign values to the fields.

const post = new Post()
post.body = 'body'
post.title = 'title'
// ... assign all the other fields

I want to validate post, skipping validation for all the fields except title. There doesn't seem to be a way to do this aside from assigning groups to all fields, which I don't want to do. Is there a way to just validate this single field?


Solution

  • No, unfortunately, there is not a way to validate just a single field without assigning groups.