Validating a DataType Model

I have a project with a classic 3-level structure: DataStore, BusinessLogic, Web-Frontend

In the DataStore, I have a model (simplified), for example. ConfigModel.cs:

public class ConfigModel { [DataType(DataType.EmailAddress)] public string DefaultSenderEmail { get; set; } public IPAddress FallbackDNS { get; set; } } 

The question arises:

What an elegant way to programmatically add Validators according to the actual DataType type or DataType attribute?

A few answers that I still considered myself, but did not find them satisfactory:

  • Add the verification attribute [EmailAddress] to the parameter: I do not want duplication, and I do not want to reference the special MVC code at my DataStore level.

  • Create separate ViewModels and use AutoMapper: since some of my models are much more complex, I would not want to create specific ViewModels.

Thanks!

+4
source share
2 answers

I would also consider using AutoMapper, but not as an answer to this solution.

Maybe you can consider this: http://weblogs.asp.net/srkirkland/archive/2011/02/15/adding-client-validation-to-dataannotations-datatype-attribute.aspx

+1
source

This is not duplication. DataType is used for different purposes, and validation is different. Although they may sound the same (especially for EmailAddress), you should not consider using both as duplicates. In addition, the check is automatically controlled for types with a zero value - they are marked as Required . Time periods are also checked for the correct format automatically.

What you definitely hate is the control over what properties of your domain model can be edited by users using BindAttribute and controlling different checks on the same when using different types. So go on to using ViewModels! Decorate them with all the attributes necessary for your web application, and return them back to the domain model using AutoMapper

You can also check FluentValidation

0
source

Source: https://habr.com/ru/post/1400369/


All Articles