Self validating model Validation is one such example where you can specify validation rules in the model class and enforce the rules everywhere else in the application. In Custom DataAnnotations we need to create a separate class derived from the ValidationAttribute base class. More information about Custom DataAnnotations can be grabbed from here.
The Remote feature provides Asynchronous Validation on the Model Self validating model. To implement asynchronous validations using Remote, we need to write action method in MVC controller that Self validating model a JsonResult. But what if that we want to validation check logic for the Model class? In this case we must provide self-validation behavior for the model class.
Self validating model do so, we use the IValidatableObject interface under System. This interface provides the Validate interface with ValidationContext input parameter.
This parameter defines Self validating model context in which validations are checked. This provides error messages generated for properties from the model class. In this project, add the following code in the Models folder by adding class file. The method contains logic for validating Income and BirthDate.
The array declared in the method is used to associate the validation result for the model property, on which validation is checked. Here we have made the Model object as a self
Self validating model object and the advantage of this approach is that we need not write a separate class for validation checks.
In the controller, add the following code for Create Action methods:. In the view we already have the Html helper method as shown here:. Run the application and enter values for Name, BirthDate, and Income.
Click on the Create
Self validating model, if values are invalid, error messages will be displayed as shown here:.
Download the Self validating model source code of this article Github. Self Validating Model objects Posted by: In the controller, add the following code for Create Action methods: In the view we already have the ValidationMessageFor Html helper
Self validating model as shown here: Click on the Create button, if values are invalid, error Self validating model will be displayed as shown here: Was this article worth reading?
Share it with fellow developers too. NET Technologies all versions. Follow him on twitter maheshdotnet.
Feedback - Leave us some adulation, criticism and everything in between! Comment posted by Fabio Ambrozio on Wednesday, April 22, It's a nice tuto! Design Patterns Software Gardening. Forms 3 - Cheat sheet Unit testing with Vue.