C
C#15mo ago
NeRooN

❔ 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
Anu6is
Anu6is15mo ago
if you do (x => ...) where? Do you mean when using .When(x => ...)
NeRooN
NeRooNOP15mo ago
yes, i add a screenshot:
NeRooN
NeRooNOP15mo ago
in the "When" method, x is T but in "Must" x is string
Anu6is
Anu6is15mo ago
you could just set your must condition to be empty or contains .Must(x => !string.IsNullOrWhiteSpace(x) || x.Contains("---"))
NeRooN
NeRooNOP15mo ago
but i want to validate the mail and the domains only when it's not null or empty, that wouldn't work as intended?
Anu6is
Anu6is15mo ago
wouldn't it? you could also try placing the when on the call to ValidEmail RuleFor(...).ValidEmail(localizer).When(...)
NeRooN
NeRooNOP15mo ago
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
Anu6is
Anu6is15mo ago
that's fair... i never actually used the builders with fluent validation but it when definitely is missing an overload similar to the must
Accord
Accord15mo ago
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.
Want results from more Discord servers?
Add your server