Jasinski Technical Wiki


Home Page
All Pages

Quick Search
Advanced Search »

Contributor Links

Create a new Page
File Management
Your Profile

Other Wiki Sections



Required Field Validation (Conditionally) - ASP.NET

Modified on Mon, Jan 17, 2011, 2:41 PM by Administrator Categorized as ASP·NET Web Forms


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.


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; } }

    . . .


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

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

ScrewTurn Wiki version Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.