data annotation attributes c#


 C# DataAnnotation   Attributes

1.Required
2.StringLengtgh
3.DisplayName
4.Range
5.Compare
6.ScaffoldColumn
7.RegularExpression
8.EmailAddress
9.Url
10.Remote
11.MinLength
12.MaxLength
13.DataType
14. custom dataAnnotation Attribute

Required : Ensures that a property has been assigned some value.
Range : Ensures that a property value falls within a minimum and maximum value.
StringLength : Can be used to check the length of a string property. You can either specify maximum permissible length or maximum and minimum permissible length.
EmailAddress : Validates that an email address with a valid email format has been supplied as a property value.
Url : Validates that a valid URL has been supplied as a property value.
RegularExpression : Uses a regular expression to ensure that a property value matches the specified pattern.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace DataAnnotationDemo.Models
{
    public class UserProfileMetadata
    {
        [DisplayName("First Name :")]
        [Required]
        [StringLength(50,MinimumLength=3,ErrorMessage="First Name must be between 3 and 50 characters!")]
        public string FirstName { get; set; }

        [DisplayName("Last Name :")]
        [Required]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Last Name must be between 3 and 50 characters!")]
        public string LastName { get; set; }

        [DisplayName("Email :")]
        [Required]
        [EmailAddress(ErrorMessage="Invalid Email")]
        public string Email { get; set; }

        [DisplayName("Profile :")]
        [StringLength(500, ErrorMessage = "Bio must be less than 500 characters!")]
        public string Bio { get; set; }

        [DisplayName("Age :")]
        [Required]
        [Range(18,100)]
        public int Age { get; set; }

        [DisplayName("Blog URL :")]
        [Required]
        [Url(ErrorMessage = "Invalid URL!")]
        public string BlogUrl { get; set; }

        [DisplayName("Phone :")]
        [Required]
        [RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",ErrorMessage="Invalid Phone Number!")]
        public string Phone { get; set; }

    }
}




we can also create the custom Attribute

steps to create the custom dataAnnotation Attribute

step 1: inherit the class from the ValidationAttribute
step 2. Override the IsValid method and add logic to perform validation.
    Return true if the custom validation is successful, or false if it fails.
step 3.Use this Attributes


ex.

 public class CustomEmailValidator : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                string email = value.ToString();

                if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))
                {
                    return ValidationResult.Success;
                }
                else
                {
                    return new ValidationResult("Please Enter a Valid Email.");
                }
            }
            else
            {
                return new ValidationResult("" + validationContext.DisplayName + " is required");
            }
        }
    }


Comments

Popular posts from this blog

how to create windows service setup in c#.net

difference between var and dynamic c#