In ASP.NET MVC there exists a ModelState class that contains ModelErrorCollection. And a ModelError represents an error the occurs during model binding.
I know that ValidationResult is returned from ValidationAttribute.IsValid Method, and validates the specified value with respect to the current validation attribute. I understand that we can inherit from validationAttribute and override IsValid() in order to write a custom model validation attribute.
Example of using ModelState: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/performing-simple-validation-cs
Example of using ValidationResult: http://www.codeproject.com/Articles/260177/Custom-Validation-Attribute-in-ASP-NET-MVC
How do these two work together? Or not work together? What is the intersection? This question is trying to understand ASP.NET MVC validation approaches better.
Why am I interested and why not just use data annotations? The answer is, I want to better understand validation for dynamic fields in ASP.NET MVC. In my product context, I will not have a model of pre-determined properties to attach validationAttributes to.
I am new to ASP.NET MVC. From my understanding of the 2 you mentioned.
ValidationResult give us the ability to custom our error message linked to a property method by simply implement the IValidatableObject
and get each model to define the Validate
method.
So from my point of view, ValidationResult is more like a feature used for configure the conditions and results of model validation.
ModelState give us the possibility to make our custom error from ValidationResult as part of the ModelState by doing ModelState.AddModelError(memberName, validationResult.ErrorMessage)
And With the combination of ValidationResult and ModelState, we can still using if (ModelState.IsValid)
in our controller while the internal behavior already contains our custom error message and validation conditions.
Patrick had posted an detailed article regarding the validation in MVC, you can refer to here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With