Mr.Deer
Mr.Deer

Reputation: 476

Model validation in C# using attributes

I am trying to Validate some not null properties using attributes in a model class following this guide

What I am trying to do is this:

[Required(ErrorMessage = "Not null allowed for my var")]
public string MyNotNullVar;

I am expecting a behaviour that at the moment of reading this variable at any part of the code throws an exception with the custom Error message ("Not null allowed for my var").

I have been trying to reach it following some guides but have not landed in any solution yet.

My finall goal is to avoid writting if(foo == null) throw new ArgumentNullException("foo"); making this automated on the model declaration.

I was thinking in something similar to ModelState.IsValid but usable also out of a controller context. It would be even better if the check can be done without adding a "validity check" line manually.

Any ideas :) ?

Upvotes: 1

Views: 812

Answers (2)

Nahue Gonzalez
Nahue Gonzalez

Reputation: 374

Your Data Annotation Attribute would be useful in case you are using .NET Core Model Binding. For instance:

<form method="post">
           <div asp-validation-summary="ModelOnly" class="text-danger"></div>
           <div class="form-group">
                <label asp-for="MyNotNullVar" class="control-label"></label>
                <input asp-for="MyNotNullVar" class="form-control" />
                <span asp-validation-for="MyNotNullVar" class="text-danger"></span>
           </div>     
           <button type="submit" class="btn btn-success">Submit</button>
</form>

In this case you would get a client side validation error message when trying to submit the empty input. You should also validate in server side using if (!ModelState.IsValid) { return View(); }

Upvotes: 0

cebilon
cebilon

Reputation: 187

First of all, you can't validate it from nowhere, even if you will create some kind of attribute u are still forced to create validation code.

If I were you, I would just simply (in this case), write static method which takes as parameter this object, then by reflection I would check it for given attributes.

For example:

public static bool HandleEmptyStringFields(this object @obj)
{
 //check if there are fields of type string and have given attribute, then validate 
 //each one and in case of being null just throw new custom exception
}

Upvotes: 1

Related Questions