ASP.NET MVC 3 validation error not firing when a complex type is used in Entity Framework

627 views Asked by At

Right now I'm working on a form to let user to post content, I want to make use of the WMD editor, so in my Entity Framework model I have a complex type named Content, it holds HTML and WMD fields.

In the form, there's a textbox for the title, and a WMD editor for Content, I used the FluentValidation framework, as follow:

public class ArticleValidator : AbstractValidator<Article>
{
    public ArticleValidator()
    {
        RuleFor(x => x.Title).NotEmpty();
        RuleFor(x => x.Content.WMD).NotEmpty();
    }
}

When I submit this form without entering anything, the client-side validation only catches the Title as invalid. If I enter something in the Title, the form submits (even though the content is empty), then the error is caught on the server-side (empty content), the page is then reloaded with the information I entered, but no error message was displayed.

It seems the complex type I created in the Entity Framework model is causing this problem. I used to have separate properties for ContentHtml and ContentWMD and it worked fine.

Is there a workaround to this without having to revert back to where I was?

1

There are 1 answers

0
Darin Dimitrov On BEST ANSWER

You cannot use nested rule definition like this:

RuleFor(x => x.Content.WMD).NotEmpty();

You need to have another validator for the Content type:

public class ArticleValidator : AbstractValidator<Content>
{
    public ArticleValidator()
    {
        RuleFor(x => x.WMD).NotEmpty();
    }
}

This being said you should not use EF models inside your views. You should use View Models and define validation rules on your view model:

public class ArticleValidator : AbstractValidator<ArticleViewModel>
{
    public ArticleValidator()
    {
        RuleFor(x => x.Title).NotEmpty();
        RuleFor(x => x.Content).NotEmpty();        
    }
}