C
C#9mo ago
Core

Can different validation attributed be applied to a field based on the active profile?

Hello, In Development I would need to apply a different validation attribute to a DTO field, without impacting performance. For example, having an extra if statement in the validation that checks the current profile and applies different validation is not the greatest idea . Gemini gave vague solution, like this:
c#
#if DEBUG
// Code specific to development environment (e.g., relaxed validation)
#else
// Code specific to production environment (e.g., stricter validation)
#endif
c#
#if DEBUG
// Code specific to development environment (e.g., relaxed validation)
#else
// Code specific to production environment (e.g., stricter validation)
#endif
Can the following be done?
c#
#if DEVELOPMENT
[DevelopmentIsValidHostnameFormat]
#else
[IsValidHostnameFormat]
#endif

public string? Hostname{ get; set; }
c#
#if DEVELOPMENT
[DevelopmentIsValidHostnameFormat]
#else
[IsValidHostnameFormat]
#endif

public string? Hostname{ get; set; }
7 Replies
Pobiega
Pobiega9mo ago
Yes, that works its not very pretty, but it works. the preprocessor runs before anything else
Core
CoreOP9mo ago
Thank you, as I see there is no DEVELOPMENT
No description
Core
CoreOP9mo ago
only DEBUG is it the same?
Pobiega
Pobiega9mo ago
No. DEBUG is the debug profile in Vs/rider Development is an environment name, and is not per compilation but per execution (via env var) And that can not be used for conditional compilation like this You'll need to do it with code instead if you want to support it at runtime
Core
CoreOP9mo ago
so if it is not compiled within an IDE, will the else statement be applied?
Pobiega
Pobiega9mo ago
Sure, if you specified the profile dotnet build -c Debug In most setups, that's the default profile Oh sorry, misread your question It doesn't matter if you use an IDE or not, DEBUG is true if the Debug configuration profile was used at compilation
Core
CoreOP9mo ago
Thank you, now I got it
Want results from more Discord servers?
Add your server