I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#?
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");
}
}