This means that enabling validation is really easy for common application scenarios, while at the same time still remaining very flexible for more advanced ones. NET MVC 2 that takes advantage of the new built-in Data Annotation validation support.Specifically, let’s implement a “Create” form that enables a user to enter friend data: We want to ensure that the information entered is valid before saving it in a database – and display appropriate error messages if it isn’t: We want to enable this validation to occur on both the server and on the client (via Java Script).We’ll choose to scaffold a “Create” view that is passed a Person object: Visual Studio will then generate a scaffolded view file for us under the \Views\Friends\ directory of our project.Notice below how it takes advantage of the new strongly-typed HTML helpers in ASP.NET MVC 2 project that looks like below: It has four properties (implemented using C#’s automatic property support, which VB in VS 2010 now supports too – woot! We’ll then add a “Friends Controller” controller class to our project that exposes two “Create” action methods.The first action method is called when an HTTP-GET request comes for the URL.The text elements with the invalid input are highlighted in red, and the validation error messages we specified are displayed to the end user about them.The form is also preserving the input data the user originally entered – so that they don't have to refill anything. To understand this behavior, let’s look at the Create action method that handles the POST scenario for our form: When our HTML form is posted back to the server, the above method will be called.
If the posted form input is invalid, the action method redisplays the form with errors: After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog.
We’ll implement these rules on our Person model object – and within our Controller or our View.
The benefit of implementing the rules within our Person object is that this will ensure that the validation will be enforced via any scenario within our application that uses the Person object (for example: if we later added an edit scenario).
This is done via the last line of code in the code snippet above.
The error messages are then displayed within our view because our Create form has helper. Validation Message For() helper will output the appropriate error message for any invalid model property passed to the view: The nice thing about this pattern/approach is that it is pretty easy to setup – and it then allows us to easily add or change validation rules on our Person class .
Alternatively you can define them within resource files and optionally localize them depending on the language/culture of the incoming user.