Roman Koliada
Roman Koliada

Reputation: 5122

FluentValidation for nested properties on the ClientSide

I have these models:

public class AssignmentTaskModel 
    {
        public AssignmentTaskModel() { }

        public AssignmentTaskModel(WorkOrderTaskDto task)  
        {
            Task = task;
        }

        public WorkOrderTaskDto Task { get; set; }
    }

public class AssignmentTaskModelValidator : AbstractValidator<AssignmentTaskModel>
{
    public AssignmentTaskModelValidator()
    {
        RuleFor(x => x.Dto).Configure(x => x.ClearValidators());

        RuleFor(x => x.Dto.Id).NotEmpty();
        RuleFor(x => x.Dto.Employee.Id).NotEmpty();
        RuleFor(x => x.Dto.EventDate).NotEmpty();
    }
}

WorkOrderTaskDto contains a lot of fields and I have a separate validator for it. I want to have only Employee.Id and EventDate as required in AssignmentTask not others from WorkOrderTaskDto, that's why I'm clearing validators at the first line.

Basically, it works well but only on the server side. It seems to me that Fluent generate client-side validation attributes only for non-nested fields. Is it possible to have client-side validation for RuleFor(x => x.Dto.Employee.Id).NotEmpty();?

Unfortunately, I can't create different validators for WorkOrderTaskDto and just SetValidator() because I in this case I will get an exception in IoC FluentValidation factory about duplicate types.

Upvotes: 1

Views: 430

Answers (1)

Breno Rezende
Breno Rezende

Reputation: 69

Unfortunately, the FluentAPI only generates the DbEntityValidationException exception. So, if you want to set NotEmpty (Required) constraint on the client side, you have to put it on the model using DataAnnotation, like the following sample.

[Required]
public DateTime EventDate { get; set; }

Hope this help you :)

Upvotes: 2

Related Questions