7

I'm working with MVC 4 for the first time. I have business logic that is a little complex but I would imagine not that uncommon. I have items that can be resized within a specific range. The range depends upon the item.

public class MyItem
{
    public double Width { get; set; }

    public double MinWidth { get; set; }

    public double MaxWidth { get; set; }
}

CustomWidth when set by a user has to be within MinWidth and MaxWidth inclusively. This seems like a common problem. I've tried the CustomValidation attribute but it only validates when I try to save the entity to my database (using Entity Framework).

This is the Razor page I'm working with.

@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) { 
<aside id="aside">
    <div class="editor-label">
        @Html.LabelFor(model => model.Width)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Width)
        @Html.ValidationMessageFor(model => model.Width)
    </div>  

    <div class="editor-label">
        @Html.LabelFor(model => model.Height)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Height)
        @Html.ValidationMessageFor(model => model.Height)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Depth)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Depth)
        @Html.ValidationMessageFor(model => model.Depth)
    </div>

    <input type="submit" value="save" />
</aside>
}
Jordan
  • 9,642
  • 10
  • 71
  • 141
  • This would work, but I don't want to couple my data layer that closely to MVC. – Jordan Mar 14 '13 at 20:32
  • It wouldn't couple the ui to the datalayer if you employed a view model – Forty-Two Mar 14 '13 at 20:50
  • Point well taken, but it would still couple the validation into the view model a bit too much for comfort. I didn't realize that returning the model after the post call would report the errors. I've grokked that now thanks to @mrcolombo. – Jordan Mar 14 '13 at 20:59

1 Answers1

8

To do custom validation, you want to inherit from IValidatableObject.

**Note custom validation will happen after initial model validation is successful

    public class MyItem : IValidatableObject
        {
            public double Width { get; set; }

            public double MinWidth { get; set; }

            public double MaxWidth { get; set; }
            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
           {
                // Custom validation
           }

}

Example on how to use

Community
  • 1
  • 1
mrcolombo
  • 587
  • 4
  • 19