How do I add custom validation to a Razor page?
asp.net-mvc, razor
Solution
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
Problem
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> } ```