title: How do I add custom validation to a Razor page?
body: <p>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. </p>
  
  <pre><code>public class MyItem
  {
      public double Width { get; set; }
  
      public double MinWidth { get; set; }
  
      public double MaxWidth { get; set; }
  }
  </code></pre>
  
  <p><code>CustomWidth</code> when set by a user has to be within <code>MinWidth</code> and <code>MaxWidth</code> inclusively.  This seems like a common problem. I've tried the <code>CustomValidation</code> attribute but it only validates when I try to save the entity to my database (using Entity Framework).</p>
  
  <p>This is the Razor page I'm working with.</p>
  
  <pre><code>@using (Html.BeginForm("Action", "Controller", FormMethod.Post)) { 
  &lt;aside id="aside"&gt;
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.Width)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.Width)
          @Html.ValidationMessageFor(model =&gt; model.Width)
      &lt;/div&gt;  
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.Height)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.Height)
          @Html.ValidationMessageFor(model =&gt; model.Height)
      &lt;/div&gt;
  
      &lt;div class="editor-label"&gt;
          @Html.LabelFor(model =&gt; model.Depth)
      &lt;/div&gt;
      &lt;div class="editor-field"&gt;
          @Html.EditorFor(model =&gt; model.Depth)
          @Html.ValidationMessageFor(model =&gt; model.Depth)
      &lt;/div&gt;
  
      &lt;input type="submit" value="save" /&gt;
  &lt;/aside&gt;
  }
  </code></pre>