Let’s re-run the application and try to create a new
Dinner. Let’s begin by pushing the “Create” button with no values filled
out. We’ll find that we now see the validation error messages we applied
to our model showing up in the browser:
Because we enabled client-side validation with ASP.NET MVC
(that was the one line of code we wrote above), our error messages will update
and change in real-time:
Notice above how our validation error message changed once
our “Title” became longer than 20 characters. This is because we have a
[StringLength] property on our Dinner.Title property that indicates a maximum
allowed size of 20 characters. As we started entering a value within the
“HostedBy” textbox, our error message likewise changed from the “[Requred]”
error message (which asks you to enter your email address) to the
“[RegularExpression]” error message (which is telling us we don’t have a valid
email address).
These validation rules work both within the browser (via
JavaScript) and on the server (enabling us to protect ourselves even if someone
tries to bypass the JavaScript validation) – without us having to make any
changes to our controller class. The ability to specify these rules once
within our model, and have them apply everywhere, is extremely powerful – and
will enable us to continue to evolve our application in a very clean way.
You can learn more about these ASP.NET MVC 2 Model
Validation features and how they work here.