2

I was wondering what the best practice is for model validation when it comes to using getters and setters. Specifically, I have nullable fields in my model that, in some use cases, should not have null values when accessed. In those cases, I would like to throw an exception from the getter, but is that an accepted practice?

This could also be the case if I received a value in a setter that was not valid.

Alternatively from throwing exceptions, I'm aware of MVC attributes that you can use to decorate fields, but have not used them very much for model validation. In the "This value shouldn't be null in my getter" scenario, is there an appropriate attribute I could use?

Also, if throwing exceptions in getters and setters is accepted, is there a recommended exception to throw, i.e. ValueNotValidException (if that were real)?

rae1
  • 6,066
  • 4
  • 27
  • 48
Matt
  • 23,363
  • 39
  • 111
  • 152
  • Seems like you just asked [that](http://stackoverflow.com/questions/14390711/net-mvc-shielding-nullable-domain-properties-with-model). – rae1 Jan 18 '13 at 01:12
  • I did, but this question is tangential, and focuses on a specific part of my other question. – Matt Jan 18 '13 at 01:17

2 Answers2

0

You should use the standard Data Validation Attributes to validate the model. If the value is required - use [Required].

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

if (ModelState.IsValid)
{
   ...
}

Less code maintain and improved readability.

Kye
  • 5,919
  • 10
  • 49
  • 84
0

If you are going to use the object as a ViewModel you can annotate it with a [NotNullValidator] given by the Microsoft's Enterprise Library, as well as a bunch of others that give extra functionality like Regex validation, ranges, IgnoreNulls, type, etc, as shown here. It is also possible using this library to create custom validators, based on this step-by-step guide, which you can use to annotate your ViewModel.

Otherwise you are left with the more traditional MVC Data Annotation Attributes, like [Required].

rae1
  • 6,066
  • 4
  • 27
  • 48