One of the things I like in C# is actually the built-in validation system in the System.ComponentModel.DataAnnotations namespace. You can have basic things like whether a property is required or a string is meant to be an email address. You can easily add your own custom validation attributes too. There is a class called Validator in that namespace with a ValidateObject function which processes it all.
The validation doesn't need to be constrained to the attributes either because if your object implements IValidatableObject, then a Validate method on your object gets called too when using Validator.
There's always the discussion as to how much should be validated using ModelState in .NET etc. too.
I find it helpful, all things equal, to have the bulk of non-trivial validation located in the same place (inside the business logic - wherever that may be).
I've worked on a system that had to validate ALL business rules client-side, then in the app layer, and finally in the DB (stored procs).
So like the exact same business rules re-done in JS, C# and then TSQL. Really weird. But that's what they wanted!
I did learn about all 3 languages really quick 😂
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I would agree that in scenarios that are not very complex there's overhead to this too.
But it really shines whenever you start dealing with complex business problems.
Some people prefer to do something like this, but instead of doing validation in the constructor they will expose some
Validate()
method.It's one of many tools 😂
One of the things I like in C# is actually the built-in validation system in the
System.ComponentModel.DataAnnotations
namespace. You can have basic things like whether a property is required or a string is meant to be an email address. You can easily add your own custom validation attributes too. There is a class calledValidator
in that namespace with aValidateObject
function which processes it all.The validation doesn't need to be constrained to the attributes either because if your object implements
IValidatableObject
, then aValidate
method on your object gets called too when usingValidator
.Keep up the good articles 🙂
Thanks! I've seen people do that too.
There's always the discussion as to how much should be validated using
ModelState
in .NET etc. too.I find it helpful, all things equal, to have the bulk of non-trivial validation located in the same place (inside the business logic - wherever that may be).
I've worked on a system that had to validate ALL business rules client-side, then in the app layer, and finally in the DB (stored procs).
So like the exact same business rules re-done in JS, C# and then TSQL. Really weird. But that's what they wanted!
I did learn about all 3 languages really quick 😂