Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Data Annotations

Data Annotations

 In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models.

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
The idea behind using data annotations is to add constraints metadata to the properties in the view model. This metadata is then picked up by the default binder when

Data Annotation Validator Attributes

DataType – Specify the datatype of a property
DisplayName – specify the display name for a property.
DisplayFormat – specify the display format for a property like different format for Date property.

The data annotations are listed and described in detail:

1.   EmailAddress: Indicates that the value must be a well-formatted e-mail address.

2.  CreditCard :Defines the value as a credit card number (15 or 16 digits without spaces or dashes).

3.  Required: Specify a property as required.

4.   ReqularExpression  : Validate the value of a property by specified regular expression pattern.

5   Range: Validate the value of a property within a specified range of values.

6.   StringLength : Specify min and max length for a string property.

7.   MaxLength : Specify max length for a string property.

8 .  Bind – Specify fields to include or exclude when adding parameter or form values to model properties.

9.   ScaffoldColumn : Specify fields for hiding from editor forms.

10.  EnumDataType(typeof(name of enum)) :Enables a .NET Framework enumeration to be mapped to a data column.The value must be one of those defined in the enumeration.

11.  FileExtension(Extensions="") : Validates that the file extension of the uploaded file is in the acceptable extensions defined; for example, [FileExtensions(Extensions=".jpg,.png,.gif")].

 

Data annotation Example:

public class Company
    {
        [Key]
        public Int16 CmpId { get; set; }
 
        [Required(ErrorMessage = "Name is required")]
        [StringLength(150)]
        [RegularExpression("^[A-Za-z0-9][A-Za-z0-9_ .-]*", ErrorMessage = "Invalid company name")]
        public string CmpName { get; set; }
 
        [Required(ErrorMessage = "Regestration number is required")]
        [StringLength(150)]
        public string CmpRegestration { get; set; }
 
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Registration Date is required")]
        public DateTime CmpRegDate { get; set; }
 
        [Required(ErrorMessage = "Email is required")]
        [DataType(DataType.EmailAddress)]
        [StringLength(150)]
        [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
        public string CmpEmail { get; set; }
 
 
        public Guid CreatedBy { get; set; }
 
        [ForeignKey("CreatedBy")]
        public aspnet_Users User { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime? CreatedDate { get; set; }
 
    }
 



 Custom Data Annotations:

You can create your own custom validations by creating custom data annotations.To create a custom annotation, you need to create a class that inherits from ValidationAttribute, and the name of that class must end with the suffix Attribute.

For example leave application has “from date” and “To date”, now you have to apply custom validation that to date should be always greater than from date.

Following example compares date, if to date is less than from Date then custom data annotation create error message.

Example:

#region Date compare Rule

    public sealed class IsDateAfter : ValidationAttribute
    {
        private readonly string testedPropertyName;
        private readonly bool allowEqualDates;
 
        public IsDateAfter(string testedPropertyName, bool allowEqualDates = false)
        {
            this.testedPropertyName = testedPropertyName;
            this.allowEqualDates = allowEqualDates;
        }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
            }
 
            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
 
            if (value == null || !(value is DateTime))
            {
                return ValidationResult.Success;
            }
 
            if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
            {
                return ValidationResult.Success;
            }
 
            // Compare values
            if ((DateTime)value >= (DateTime)propertyTestedValue)
            {
                if (this.allowEqualDates)
                {
                    return ValidationResult.Success;
                }
                if ((DateTime)value > (DateTime)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }
 
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessageString,
                ValidationType = "isdateafter"
            };
            rule.ValidationParameters["propertytested"] = this.testedPropertyName;
            rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
            yield return rule;
        }
    }

    #endregion

 

Use of custom validation:

   public class Leave
    {
        [Key]
        public int LeaveId { get; set; }
 
        public BlogProj.Models.Enum.LeaveCatogry LeaveCatogry { get; set; }
 
        [Display(Name = "From")]
        public DateTime? FromDate { get; set; }
 
        [Display(Name = "To")]
        [IsDateAfter("FromDate", true,ErrorMessage="To date should be after from date")]
        public DateTime? ToDate { get; set; }
  }



Invalid entry,please enter valid data.

Loading