'Fluent validator: How to validate a string to be not empty when another field is specific value from enum
I need to add validation for Message only when Type is Other
I tried to use Must, and validation works when type is Other, but when type is First I receive "The specified condition was not met for 'message'.",
enum Types
{
First, Second, Other
}
class MyRequest
{
public string Message { get; set; }
public Types Type { get; set; }
}
public MyRequestValidator()
{
RuleFor(x => x.Type)
.IsInEnum();
RuleFor(x => x.Message)
.Must((model, field) =>
{
if (model.Type == Types.Other)
{
return true;
}
return false;
})
.NotEmpty()
.WithMessage("Message is required when type is Other")
.MaximumLength(10);
}
Any ideas how to validate a string when another prop is a specific value from an enum?
Solution 1:[1]
looks like When proposed by SaeedEsmaeelinejad soled my issue
When(x => x.Type == Types.Other, () => {
RuleFor(x => x.Message)
.NotEmpty()
.WithMessage("Message is required when type is Other")
.MaximumLength(10);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex |
