Validation without the "ModelState.isValid"


I have the following scenario:

    public PartialViewResult Create(string dados)
        var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
        if (ModelState.IsValid) { } // Não têm como validar.

I get json and convert to the ClientViewModel object, but this way I can not validate with "ModelState.isValid" because it validates the template that is in the parameter.

I do not want to have to send the form normally to the Action and in its parameter put the ClientViewModel instead of the "data string (json)" as this causes the whole page to be loaded, and I do not want this. >

Is there a way to validate the ViewModel in this way?

asked by anonymous 25.11.2016 / 18:52

2 answers


You can not do it this way below: if the attributes are exactly the same name as the viewmodel it can receive all the parameters and does not need to deserialize.

    public PartialViewResult Create(ClienteViewModel model)
        if (ModelState.IsValid) { }
25.11.2016 / 18:57

Ideally, it should be validated by ModelState , as shown in the @EduardoSampaio response. However, you can validate otherwise.

To do the validation, you need to use the class ValidationContext.

An example would be this:

var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
List<ValidationResult> restuls = new List<ValidationResult>();
ValidationContext context = new ValidationContext(clienteViewModel, null, null);

bool isValid = Validator.TryValidateObject(clienteViewModel, context, restuls, true);

if (!isValid)
    foreach (var validationResult in restuls)
        var pause = true;

Another option would be to use DataAnnotations Validator .

Just install the package with the following command:


Install-Package DataAnnotationsValidator

And to use, just do the following:

var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
var validator = new DataAnnotationsValidator.DataAnnotationsValidator();
var validationResults = new List<ValidationResult>();

var isValid = validator.TryValidateObjectRecursive(clienteViewModel , validationResults);

The original package code you can see in this answer the author . But in short, it only uses ValidationContext in the same way.

If you'd like to learn more, you can look at this article and this answer.

25.11.2016 / 20:14