I am trying to work out client side validation and have followed a couple of tutorials , it looks quite simple but i have no idea why its not working on my project, below is the code:
<script type="text/javascript" src="/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="/Scripts/jquery.validate.js"></script>
<script type="text/javascript" src="/Scripts/MicrosoftMvcJQueryValidation.js"></script>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary("Please Correct the errors and try again")%>
<div class="editor-label">
<%: Html.LabelFor(model => model.test,"Test") %>
</div>
</td>
<td>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.test)%>
<%: Html.ValidationMessageFor(model => model.test)%>
</div>
</td>
</tr>
edited: master page
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery-1.5.1.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery.validate.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery.validate.unobtrusive.js") %>"> </script>
<script src="/Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/Scripts/tiny_mce/jquery.tinymce.js"></script>
<script src="/Scripts/ie6.js" type="text/javascript"></script>
Any ideas Why the client side validation doesnt works when I press tab for that field.
In ASP.NET MVC 3, jquery
and jquery.validate
are the default frameworks for doing client side validation. So modify your code to look like this:
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery-1.5.1.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery.validate.js") %>"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/jquery.validate.unobtrusive.js") %>"></script>
<% using (Html.BeginForm()) { %>
<%= Html.ValidationSummary("Please Correct the errors and try again") %>
<div class="editor-label">
<%= Html.LabelFor(model => model.test, "Test") %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.test) %>
<%= Html.ValidationMessageFor(model => model.test) %>
</div>
<% } %>
Things to notice:
jquery.validate.js
jquery.validate.unobtrusive.js
which unobtrusively attaches the jQuery.validate plugin to HTML5 data-* attributes emitted by the Html helpers.Url.Content
helper to reference static resources instead of hardcoding their locations.Html.EnableClientValidation()
Microsoft*
One final note: make sure that in your web.config unobtrusive client script validation is enabled:
<appSettings>
...
<add key="ClientValidationEnabled" value="true" />
</appSettings>
The best way to get the latest versions of those scripts is to install the ASP.NET MVC 3 Tools Update, create a new ASP.NET MVC 3 project using the default wizard in Visual Studio and fetch those 3 scripts.