How to make a value type mandatory for ASP.NET MVC validation?

Good afternoon!

I have a model associated with a JSON request, for example:

public class MyModel { public bool isSomeFeatureEnabled { get; set; } } 

And a controller like this:

 public ActionResult Submit(MyModel request) { if (ModelState.IsValid) { .. } else { .. } } 

When I send an empty JSON object to this action ( {} ), it will be valid with isSomeFeatureEnabled=false . But I want this field to be β€œrequired” in terms that it should always be set to a specific value (true \ false).

I can make this field null and put [Required] on it, but this field is really not valid for every model logic.

Same story with int , double and DateTime fields.

I am using ASP.NET MVC 3 and the default setting is:

 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true 

Shouldn't this work for this situation?

+4
source share
2 answers

I think making this field null and also making it Required better shot. As the book says,. Otherwise, you can write your own attribute so that the validate method returns false when passed to value = default(T)

+2
source

Given the update, that JSON comes from a third-party API, and you have no influence on its formation; it seems like a null value is the way to go.

+2
source

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


All Articles