Validate Nullable Enum Values using Fluent Validation

69 Views Asked by At

I have a nullable list of Enumeration and I would like to validate the enum only if the list is NOT null. I do see option to validate for Null & IsInEnum. But would like to do only if the employeeTypes IS NOT NULL. How can I achieve this?

public enum EmployeeType
{
    LEVEL_1 = 1,
    LEVEL_2 = 2,
    LEVEL_3 = 3,
    LEVEL_4 = 4
}

public async Task<IActionResult> GetEmployeesAsync(List<EmployeeType>? employeeTypes)
{
   //TODO: I want to move this to Fluent Validation
   if (employeeTypes!= null && employeeTypes.Any(x => !Enum.IsDefined(x)))
   {
    return BadRequest("employeeTypes parameter is Invalid");
   }
   
   //Return employees based on employeeTypes if not null, else return all employees
   var employees = await _engine.GetEmployes(employeeTypes);
   return Ok(employees);
}


2

There are 2 best solutions below

0
On

I added a custom validation for the enumeration and worked around with this problem for now. Let me know if there is a better solution.

private static bool IsValidEmployeeTypes(List<LeadType>? employeeTypes)
{
    if (employeeTypes == null || employeeTypes.Count == 0)
    {
        return true;
    }

    return employeeTypes.All(Enum.IsDefined);
}

Then called the above method from the Validator function as below:

RuleFor(x => x.employeeTypes)
    .Must(IsValidEmployeeTypes)
    .WithMessage("Invalid value for employeeTypes");

1
On

Please, take a look at:

  static void Main() {
    Console.WriteLine("Hello World");
    
    EmployeeType a = new EmployeeType();
    EmployeeType? b = new EmployeeType();
    
    Console.WriteLine("a:{0} b:{1}", a, b);
    a = EmployeeType.LEVEL_2;
    b = EmployeeType.LEVEL_3;
    Console.WriteLine("a:{0} b:{1}", a, b);
    
    a = (EmployeeType)6;
    b = (EmployeeType)7;
    Console.WriteLine("a:{0} b:{1}", a, b);
    
    foreach(var item in System.Enum.GetValues(typeof(EmployeeType))) {
        Console.Write("{0}, ", item);
    }
    Console.WriteLine();
  }
  
  public enum EmployeeType
{
    LEVEL_1 = 1,
    LEVEL_2 = 2,
    LEVEL_3 = 3,
    LEVEL_4 = 4
}

output:

Hello World
a:0 b:0
a:LEVEL_2 b:LEVEL_3
a:6 b:7
LEVEL_1, LEVEL_2, LEVEL_3, LEVEL_4, 

see: https://onlinegdb.com/saNCB96Nmq

One could extend this example using a List, see: https://onlinegdb.com/zJN7LrnhX