fluentvalidation-ts icon indicating copy to clipboard operation
fluentvalidation-ts copied to clipboard

[Question/Possible Enhancement] Can I specify the whole object in ruleFor(...) instead of a property?

Open bharrison-od opened this issue 4 years ago • 1 comments

I have used https://fluentvalidation.net/, which the docs for this library reference as an influence for this library, and indeed they do look very similar. In the C# version, I can write RuleFor(x => x).Must(...);, and I'm wondering if there is any way to do the same here? Something akin to the following

import { Validator } from 'fluentvalidation-ts';

type FormModel = {
    name: string;
    age: number;
};

export default class MyValidator extends Validator<FormModel>
{
    constructor() {
        super();

        this.ruleFor(x => x) // This isn't allowed. I don't want to specify a property here.
            .must(x => x.name === "test" && x.age === 5);
    }
}

I realize I could do something like

this.ruleFor("name").must((_, x) => x.name === "test" && x.age === 5);

but that feels like a hack. I also realize that it would be more proper to break this into 2 validation rules, 1 for name and another for age. This was just a quick example to illustrate the goal.

Thanks in advance!

bharrison-od avatar Jul 23 '21 01:07 bharrison-od

Hi there - thanks for your feedback, and sorry it's taken me so long to get back to you on this!

Adding greater detail and flexibility to the shape of the validation result object (likely taking further inspiration from the C# library) is something I've been thinking about for a while, and having "top-level" validation errors would ultimately be part of that change.

In short: this is on my radar, and should be included when I finish off the next major release 😄

AlexJPotter avatar Sep 06 '21 08:09 AlexJPotter