Required Field Validation (Conditionally) - ASP.NET

Overview

The System.ComponentModel.DataAnnotations .NET namespace provides a number of attributes you can use to implement data validation: Required(), Range(), etc. This article demonstrates how to validate any field based on the value of another field; AND (this is the important part) have the validation message be at the field level rather than the class level. This second part is what allows us to place a validation message next to the invalid field on a web page.

Solution

In our example, we have the business rule that when a Claim entity is submitted (i.e., when SubmittedOn is non-null), the LossValue field is required.

C# Code

The following code is placed in its own file, OUTSIDE of the code file generated by the Entity Framework.

public partial class Claim
{
    private bool IsSubmitted{get { return (this.SubmittedOn != null); }}

    [Required(ErrorMessage = "Loss Value is required for a submitted claim.")]
    public decimal? LossValueExt { get { return IsSubmitted ? LossValue : 0; } }

    . . .
}

ASPX Code

The following code is placed on the page near the Loss Value textbox.

<%: Html.ValidationMessageFor(m => m.Claim.LossValueExt) %>