Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Required Field Validation (Conditionally) - ASP.NET

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

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) %>

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