Thursday 20 August 2015

Custom compare Validate in the MVC model

We can use data annotations for the model level validations for most scenarios.  There are situations where we need to go beyond than data annotation validations and following is a data comparison example where we need to use extensive validations.

In this example we are using IValidatableObject in our model class in order to implement the date compare validation.

    
   public class LeaveApply : IValidatableObject
    {
        [Key]
        [HiddenInput(DisplayValue = false)]
        public int LeaveKey { get; set; }

        [Display(Name = "Employee")]
        public int EmployeeId { get; set; }

        [ForeignKey("EmployeeId")]
        public Employee Employee { get; set; }
      

        [Display(Name = "Date From")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateFrom  { get; set; }

        [Display(Name = "Date To")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateTo { get; set; }

       

        public IEnumerable< ValidationResult>  Validate(ValidationContext validationContext)
        {
            if (DateTo < DateFrom)
            {
                yield return new ValidationResult("Date To must be greater than Date From");
            }
        }
    }

No comments:

Post a Comment