Validate Enum Values

前端 未结 11 1002
你的背包
你的背包 2020-11-30 09:43

I need to validate an integer to know if is a valid enum value.

What is the best way to do this in C#?

11条回答
  •  被撕碎了的回忆
    2020-11-30 10:09

    You can use the FluentValidation for your project. Here is a simple example for the "Enum Validation"

    Let's create a EnumValidator class with using FluentValidation;

    public class EnumValidator : AbstractValidator where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        public EnumValidator(string message)
        {
            RuleFor(a => a).Must(a => typeof(TEnum).IsEnum).IsInEnum().WithMessage(message);
        }
    
    }
    

    Now we created the our enumvalidator class; let's create the a class to call enumvalidor class;

     public class Customer 
    {
      public string Name { get; set; }
      public Address address{ get; set; }
      public AddressType type {get; set;}
    }
    public class Address 
    {
      public string Line1 { get; set; }
      public string Line2 { get; set; }
      public string Town { get; set; }
      public string County { get; set; }
      public string Postcode { get; set; }
    

    }

    public enum AddressType
    {
       HOME,
       WORK
    }
    

    Its time to call our enum validor for the address type in customer class.

    public class CustomerValidator : AbstractValidator
    {
        public CustomerValidator()
       {
         RuleFor(x => x.type).SetValidator(new EnumValidator("errormessage");
      }
    }
    

提交回复
热议问题