Search code examples
asp.net-mvcnancy

Validate Models And User Input In Nancy


What is the current method to validate Models in Nancy (Nancy FX?)?

Is it to roll my own, use DataAnnotations or for each class should I also implement an AbstractValidator?

I am attempting to validate many Models - my user registration page and regular model post pages. When using AbstractValidator; in my Module class do I call .BindAndValidate<Foo>() or .Validate(fooInstance)?

This post describes one method but its 3 years old so there may be newer ways?


Solution

  • There is one way to do validation i.e invoking this.Validate(instance). BindAndValidate<>() does literally that i.e first it binds the model then it invokes Validate on it.

    The Validate method will search for a validation factory which will create the actual validators for the model. I'm using fluent validation so in my case it invokes the defined validators.

    I can't help you with data annotations since I don't use it, but with FluentValidation I just install the Nancy.Validation.FluentValidation package (nuget) and then I define the validators. That's it. I'm assuming a similar approach with data annotation.

    Note that .BindAndValidate() sets the validation result in Context.ModelValidationResult .