Monthly Archives: April 2021

Validation in MVC and its different way of implementation


We can implement validation in two ways
1) Client side validation
2) Server side validation

In Server side by default we make use of existing validation through DataAnnotations
Declare default validation attribute like “Required”, “RegularExpression” , “Range” on top of required class properties to enforce certain rules.

Other way is by implementing IvalidatableObject

1) This interface contain Validate(), its return type is Ienumerable
2) By implementing IvalidatableObject interface in a class and implement our own custom rules and condition inside the Validate()
3) Since it could be implement our own custom rules and condition it is easy for cross validation property
But the same has limitation in reusability because sometime it become tightly coupled.

Model binding in controller
> By default model validation handled during model binding process, when data requested and start binding with class property, it apply assigned attribute validation attribute classes to check data is correct.
> For validation implemented using IvalidatableObject interface will happen next to prebuilt validation, this is because to check each property has loaded with correct and required data, before implemeting cross validation property.
> After this two steps completed the results of validation stored in “ModelState” property of Controller. So even when we implement our custom validation using IvalidatableObject interface, those validation result will also automatically updated in “ModelState.IsValid” property

The other way is by using ValidationAttribute class as below

%d bloggers like this: