Friday, January 8, 2016

Create Custom Validator - ASP.NET MVC

In this example I am using a sample class called Employee class. I do a custom validation for the field "Date of birth". The Employee class looks something like below. Notice that the class inherits the IValidatableObject interface in order to implement the custom validation. Afterwards the Validate() method is implemented.

    public class Employee : IValidatableObject
    {
        public virtual int ID { get; set; }

        [Required]
        public virtual string Name { get; set; }
        public virtual string Address { get; set; }
        public virtual DateTime DateOfBirth { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var field = new[] { "DateOfBirth" };
            if (DateOfBirth > DateTime.Now)
            {
                yield return new ValidationResult("Invalid date of birth", field);
            }
        }
    }

If you don't use a second parameter when instantiating the ValidationResult object, then the validation message would show up on the top of the form in the Validation summary section

Result


No comments:

Post a Comment