❔ Fluent validation custom method
Hello!
I am trying to do a generic method to validate all the mails in any DTO i have.
Since i have multiple DTO's containing email strings and the rules for all should be always the same, i wanted to do a generic method to keep it simplier to mantain in the long term.
I've read the official documentation and i was trying to follow it:
public static IRuleBuilderOptions<T, string?> ValidEmail<T, TElement>(this IRuleBuilder<T, string?> ruleBuilder)
{
}
the thing here is i have to check the email domains so they belong to specific domains and i'm achieving this with a .Must(....) and .EmailAddress().
The problem i'm facing is that i only need it to validate the must and the email address only when it's NOT null or empty, so it's optional. But unlike in the Must method, if i do (x =>...) X is from type T instead of string? so how can i do this?
9 Replies
if you do
(x => ...)
where? Do you mean when using .When(x => ...)
yes, i add a screenshot:
in the "When" method, x is T but in "Must" x is string
you could just set your must condition to be empty or contains
.Must(x => !string.IsNullOrWhiteSpace(x) || x.Contains("---"))
but i want to validate the mail and the domains only when it's not null or empty, that wouldn't work as intended?
wouldn't it?
you could also try placing the when on the call to ValidEmail
RuleFor(...).ValidEmail(localizer).When(...)
yeah, that would be a way to go, i just wanted to have it all in the same place so i just do .ValidEmail(localizer) and i had the same conditions all over the emails without the chance to forget about the "When"
so if in case i dont need anymore the "when" for some reason, i don't have to go 1 by 1 deleting it
that's fair... i never actually used the builders with fluent validation but it when definitely is missing an overload similar to the must
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.