Home > ASP.NET MVC > Custom validation in ASP.NET MVC 3

Custom validation in ASP.NET MVC 3


As you may know that you can implement validation using validation attributes that come in (System.ComponentModel.DataAnnotations namespace) in MVC , although there are numbers of  validation attributes are provided by the framework like  [Required], [Range],  [StringLength], Compare and [RegularExpression]  but it might not fulfill your business requirements, in this case you can write your own validation attribute and use the way you use framework validation attribute so to use custom validation , first write a class that inherit from abstract ValidationAttribute class and  override virtual  IsValid method with your business requirement of this class and then use it as validation attributes.  let’s implement a basic CreditCard custom validation rule .

Step 1  : Writing a class that inherit from ValidationAttribute class

public class CreditCardAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var number = Convert.ToString(value);
            if (String.IsNullOrEmpty(number))
                return true;

            return IsValidCardNumber(number);
        }

        private bool IsValidCardNumber(string cardNumber)
        {
            if (Regex.IsMatch(cardNumber, "^(4)"))
                return cardNumber.Length == 16;
            return false;
        }

        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field contains an invalid credit card number.";
        }
    }

Step 1 : Putting this as validation attribute

public class User
    {
        [CreditCard]
        public string CreditCard { get; set; }
    }

I hope I could put as simple as possible . Thanks for being around on this post :).

Advertisements
Categories: ASP.NET MVC Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: