I’m new to MVC3, and for the first time I will validate a form.
I saw some validation samples using jQuery and using Model.IsValid but I don’t know if this is my case.
I’m using @Html.TextBox, and @Html.ValidationMessage, I can see I need to place 2 jQuery lines in my document to validate:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
And I saw that many people use validation only with jQuery, but I couldn’t get how it really works. So, could you please give me a sample validation code for the Razor View with jQuery (if needed) and for Controller? As I’m not using TextBoxFor, I believe I can’t use validation only with Datannotations in the Model class.
The form I need to validate:
@Html.TextBox("user", "User:")
@Html.TextBox("email", "Email:") <!-- with validation of email string -->
@Html.Password("password")
@Html.Password("passwordConfirm") <!-- with validation if 2 password strings match -->
The
jquery.validate.unobtrusive.min.jsscript works in conjunction with data annotations placed on your model properties. Those validator attributes are then translated by the Html helpers to emit HTML5 data-* attributes which are used by the script. If you don’t have a model decorated with validation attributes you cannot use this script.This being said you could still have a model with validation attributes on it and still use the TextBox instead of TextBoxFor. It would be completely stupid and meaningless but you can do it:
and then in your view when you use one of the helpers inside a form validation attributes will be emitted:
If you don’t have a view model (don’t know why you won’t have a view model as this goes against good practices that I preach for) you could manually wire up validation. In this case you simply remove the
jquery.validate.unobtrusivescript and use the core jquery validate plugin:Obviously the recommended solution is to use a view model and strongly typed helpers:
and then in your view: