'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 1:[1]

I noticed this and it works for me.

A workaround way is that you only pass one field and validate with 'skipMissingProperties' option.


const exampleModel = new ExampleModel();
exampleModel.password = '123abc'

const errors = await validate(exampleModel, { skipMissingProperties: true })

Solution 2:[2]

Just loop over the validation errors and only act on the fields that match.

async function validateField(obj, field) {
    try {
        await validateOrReject(obj);
    } catch (errors) {
        errors.forEach((err) => {
            if(field == err.property) {
                //do something
            }
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yuji
Solution 2 Nick Wiltshire