Tuesday, 1 October 2013

Custom Validation Attribute in ASP.NET

Custom Property Validation Attribute

Above mentioned value defined as " User defined custom attribute "

Normally .Net developers used following types of attribute

- Compare
- Range
- Required
- RegularExpression
- StringLength
- Authorize

MSDN defined namespace
- using System.ComponentModel.DataAnnotations;

Step 1: But we are creating our own defined attributes in C#

Consider , we want to check weight can't be more than 100 to be entered by end user on web site

[Note: Just for your code beautification make folder in solution as Infrastructure or any]
I created folder as MVC Infrastructure in solution.
namespace BlogManagement.Infrastructure
{    public class RanegDieIdAttribute : RequiredAttribute
   {         public override bool IsValid(object value)
                    return base.IsValid(value) && ((double)value) > 100; 

Step 2:
In  Models of MVC project , create class as IDValidation.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web; using System.ComponentModel.DataAnnotations; using System.Globalization;
using BlogManagement.Infrastructure;

 namespace BlogManagement.Models
public partial class IdMast
public class IdMast_validation
  [Required(ErrorMessage = "Please enter ID")]       
  [RegularExpression("^[0-9]+$", ErrorMessage = "Field of age is not a number")]
  public string DiId
  {     get;set;
 [Required(ErrorMessage = "Please enter Weight ")]       
 [RangeDieId(ErrorMessage="Weight can not be more than 100")]       
  public double CutWt
  {    get;set;


Please check output as shown in image...

happy Coding...!!  
Live green,...say green, ...  keep green...



No comments:

Post a Comment