Reputation: 3432
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?
Upvotes: 5
Views: 4991
Reputation: 745
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
}
}
}
}
Upvotes: 0
Reputation: 441
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 })
Upvotes: 1
Reputation: 13539
No, unfortunately, there is not a way to validate just a single field without assigning groups.
Upvotes: 3