Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: IValidator additional property

$
0
0
Ended up getting pretty close to what I wanted by implementing my own types.
   public interface IEnhancedValidator<T>
    {
        IValidatorDescriptor CreateDescriptor();
        ValidatorDescriptor<T> CreateTypedDescriptor();
    }
    public abstract class EnhancedValidator<T> : AbstractValidator<T>, IEnhancedValidator<T>
    {
        public ValidatorDescriptor<T> CreateTypedDescriptor()
        {
            return (ValidatorDescriptor<T>)CreateDescriptor();
        }
    };
Seems like you would want to do the above changes in the classes you are using. As you can see it is just a typed version of CreateTypedDescriptor and is an easy implementation.

Overall, I will share with you what I am doing.
I have commands - these commands have validation. I then have a user of that command - in this case an MVC controller action. That controller action calls the commands, it is validated - validation results end up on the client. However, I would like to have client side validation on the controller action too. I could duplicate all the command validation in the view model (BAD) or I could include the command in the view model, but then that ties it directly to the view model, plus I cannot use data annotations on those command properties. What I ended up with was this:

Everyone uses EnhancedValidator<> above for validation.
The command writes normal validation.
The view model writes normal validation.....but for the properties the view model has that the command model also validates you copy those. Here is an example view model, where two properties grab the client side validation rules from the command and the other property just has regular validation:
var validatorDescriptor = changePasswordCommandValidator.CreateTypedDescriptor();
RuleFor(x => x.NewPassword).ApplyClientSideRules(validatorDescriptor.GetRulesForMember(x => x.NewPassword));
RuleFor(x => x.CurrentPassword).ApplyClientSideRules(validatorDescriptor.GetRulesForMember(x => x.CurrentPassword));
RuleFor(x => x.ConfirmPassword).NotEmpty().Length(7, 40).Equal(y => y.NewPassword);
......constructor has injected the changePasswordCommandValidator, so has parameter like this...
IEnhancedValidator<ChangePasswordForCurrentUserCommand> changePasswordCommandValidator
Works great. I have client side validation, but all the validation code is in the command where it belongs.

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>