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);
}
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.
Then called the above method from the Validator function as below: