-1

I must run the validation of a specific model after it has been submitted.

I know there are the ValidateModel/TryValidateModel and TryUpdateModel/UpdateModel but that is not good enough.

I need to perform a deep model state validation of a model. I tried getting the validation of each property and inner properties individually but the ModelState entry does not get the prefix which is obviously necessary.

Fabio Milheiro
  • 8,100
  • 17
  • 57
  • 96
  • Have you tried watching input key value pairs? In a POST, all values in input tags are submitted to the server as key-value pairs. look at the dictionary in modelstate perhaps. – DukeDidntNukeEm Sep 15 '16 at 15:53
  • I know how things are done and what I asked is how do I get MVC to do the validation that it also does on the POST. – Fabio Milheiro Sep 15 '16 at 15:55
  • why can't you inherit from IValidatableObject and then call Validate() on the model. – Fran Sep 15 '16 at 16:47
  • Because I have custom data annotations that are tested and work in several field types that do server-side and client-side validation. I didn't ask for alternatives. All I am asking is if someone can please share a way of validating the whole model again the same way the model binder does before the request reaches the action method. – Fabio Milheiro Sep 15 '16 at 16:50
  • >Because I have custom data annotations<. That important information you might want to put in the question. like how are you validating and some of the "deep" model you are validating. Given the limited information you provided. having all your models inherit from IValidateableObject and calling Validate() on the root model would do exactly what you are asking for. – Fran Sep 15 '16 at 17:15
  • you could also explain why ValidationModel isn't good enough. what is it doing/not doing that makes it unacceptable. – Fran Sep 15 '16 at 17:16
  • @Fran, my apologies for the lack of information. You are right. Sorry about that. We need data annotations because we want to have server and client-side information and, in my opinion, it is much more desirable to annotation properties in view models than having methods implemented in our view models that validate imperatively. – Fabio Milheiro Sep 15 '16 at 17:41
  • This may help you http://stackoverflow.com/questions/2493800/how-can-i-tell-the-data-annotations-validator-to-also-validate-complex-child-pro It seems you can't do it with attributes alone. – Fran Sep 15 '16 at 17:48

1 Answers1

0

I used Validator.TryValidateObject and Validator.TryValidateProperty.

This adds the errors to the input parameter validationResults and also sets the ModelState everytime (while deleting the model state error from the prior field).

It is not ideal but I get all errors and, for each error, I build the error key and save it a list.

At the end, I clear the model state and save all errors. It works. Thanks @Fran for his suggestion.

Fabio Milheiro
  • 8,100
  • 17
  • 57
  • 96