Reputation: 771
I am working with Fluent Validation
in which I am writing a custom validation that checks that the current value of the property contains any of a list of values like so:
IRuleBuilderOptions<T, TProperty> IsOfValue<T, TProperty> rule, params TProperty[] validOptions)
{
return rule
.Must(validOptions.Contains)
.WithMessage("Custom Error")
}
My issue is... How can I alter the Must(validOptions.Contains)
so that when the value is of type string, Ignore case?
I can do this easily for variants that are not utilizing lists, but can't figure out the logic to use here.
I know that I need to use either StringComparer.IgnoreOrdinalCase
or StringComparison.IgnoreOrdinalCase
depending.
Upvotes: 1
Views: 548
Reputation: 14477
You can create a specialized version of that generic method, and it would be called instead:
public static IRuleBuilderOptions<T, TProperty> IsOfValue<T, TProperty>(this IRuleBuilder<T, TProperty> rule, params TProperty[] validOptions)
{
return rule
.Must(validOptions.Contains)
.WithMessage("Custom Error");
}
public static IRuleBuilderOptions<T, string> IsOfValue<T>(this IRuleBuilder<T, string> rule, params string[] validOptions) => rule.IsOfValue(StringComparer.OrdinalIgnoreCase, validOptions);
public static IRuleBuilderOptions<T, string> IsOfValue<T>(this IRuleBuilder<T, string> rule, StringComparer comparer, params string[] validOptions)
{
return rule
.Must(x => validOptions.Contains(x, comparer))
.WithMessage("Custom Error");
}
Upvotes: 0
Reputation: 46239
You can try to check TProperty
type, if is string
you can use
string.Contains(x.ToString(),StringComparer.OrdinalIgnoreCase)
otherwise use your default.
IRuleBuilderOptions<T, TProperty> IsOfValue<T, TProperty>(this IRuleBuilder<T, TProperty> rule, params TProperty[] validOptions)
{
IRuleBuilderOptions<T, TProperty> result = rule
.Must(validOptions.Contains)
.WithMessage("Custom Error");
if(typeof(TProperty) == typeof(string)){
string[] vailds = validOptions as string[];
result = rule
.Must(x => vailds.Contains(x.ToString(),StringComparer.OrdinalIgnoreCase))
.WithMessage("Custom Error");
}
return result;
}
Upvotes: 2