Search code examples
c#excelfilevalidation

How to use data annotation validation in c# while doing file export using excel files


im doing file export functionality with Excel in C#. I have used data annotation for model validation. I have two column values such as Department, SubDepartment. If both values are same should return validation error message. How to do this using Data Annotation like model validation. I have used excel parsing for parsing data and mapping to this data model.

    public class Product
    {
        public int Id { get; set; }

        [Required]
        [StringLength(10)]
        public string Name { get; set; }

        public string Department { get; set; }

        public string SubDepartment { get; set; }
    }

im expecting solution by using data annotation or any alternative to do this validation,


Solution

  • Try this

    For this you can use CustomValidation Decorate your Entity class with an attribute like this:

    CustomValidation(typeof(MyEntity), "ArePropertiesEqual")]
    Public class MyEntity
    {
    public string prop1 { get; set; }
    public string prop1 { get; set; }
    }
    

    And implement a function called: ArePropertiesEqual like this:

    public static ValidationResult ArePropertiesEqual(MyEntity myEntity, ValidationContext validationContext)
    {
        if(myEntity.prop1 != myEntity.prop2) 
                            return new ValidationResult("propertiesdont match", new[] { "prop1", "prop2" });
    
    
        return ValidationResult.Success;
    }