There are many types of validations that do allow in MVC Models such like Required Field Validator, Data Type Validator, Range Validator and etc… But there is a way that the developer can write his own Validation Rules and work with them as a normal validator that comes built-in. This is way far easier in MVC.

First Create a New MVC 3 Application. Create a new class in the Model or can use the existing one as well. Add a reference to System.ComponentModel.DataAnnotations.

using System.ComponentModel.DataAnnotations;

In this case, I am going to use as sample model named User for the validation.

public class User
    {
        public int UserID;
        public string Gender;
        public string Salution;
        public string UserName;
        public string FirstName;
        public string LastName;
        public DateTime RegistrationTime;
    }

I do need to validate the inputs{“Male” or “Female”} for Gender of the User and I would like to name that controller as GenderValidation.

Here comes the action.

Define a class named GenderValidationAttribute that inherits from ValidationAttribute. Then override the method IsValid from the Base class.

public class GenderValidationAttribute : ValidationAttribute
    {

          protected override ValidationResult  IsValid(object value,
 ValidationContext validationContext)
        {
            string gender = value.ToString();

            if (!(value.Equals("Male") | value.Equals("Female")))
            {
                return new ValidationResult("Invalid Input for Gender.");
            }
            return ValidationResult.Success;
        }

    }

Now this can be used as normal as a general Validation Attribute. Change the User Model like below.

public class User
    {
        public int UserID;
        [GenderValidation]
        public string Gender;
        public string Salution;
        public string UserName;
        public string FirstName;
        public string LastName;
        public DateTime RegistrationTime;
    }
, , ,
Trackback

no comment untill now

Add your comment now