Shared Validations

Where are shared validations typically stored? For example, say I have a User resource that has an email that has format and length requirements. Say there was a second resource where I wanted to share those same validations. Where would I store that? Normally I would put it in the MyApp.Accounts.User.Validations.Email module, but I'm not sure if that's appropriate to share across resources as a validation. The only alternative I can think of is having something like MyApp.Accounts.Shared.Validations.Email to make it clear this is a shared validation. Is there a best practice when it comes to this?
Solution:
There's no hard rule, but for me it's typically just MyApp.Domain.Validations...
Jump to solution
5 Replies
Solution
ZachDaniel
ZachDaniel4mo ago
There's no hard rule, but for me it's typically just MyApp.Domain.Validations...
Steve
SteveOP4mo ago
Yeah, I thought about something like that, but usually I like to alias the validations module itself instead of the module, so like alias MyApp.Accounts.User.Validations then I can just do Validations.Attribute when needed. If I used a MyApp.Accounts.Validations then I whouldn't necessarily be able to do that. My thinking for the shared one was that I could alias the shared space MyApp.Accounts.Shared and then in the code do Shared.Validations.Attribute so it was obvious at a glance that it was a shared one. That was my reasoning, but I wasn't sure if this was an issue peope ran into often or if there was a pattern that was already generally considered best practice.
ZachDaniel
ZachDaniel4mo ago
it's an interesting idea. Only concern i'd have is to what degree it's shared for example. you can have app wide shared behavior too if you're doing it just for that nice alias, you'd have a conflict at some point
kernel
kernel4mo ago
alias Validations and then have modules within that? I usually just do __MODULE__.Validations.ValidateSomething I've never been against a little bit of duplication personally, I think the DRY thing can be an anti-pattern sometimes obviously It All Depends®
Steve
SteveOP4mo ago
I ended up going with this, mixed with what kernel said. So, as an example, it would be MyApp.Accounts.Validations.ValidateEmail

Did you find this page helpful?