I'm trying to use the jQuery validation plugin on a simple MVC 4 application - something I've done in MVC 3 with no problems, but I can't get it working at all.
I want the validation to fire when:
1 - my control looses focus .
2- on form submit.
Any ideas on what I've missed would be appreciated !
Script references in _Layout.cshtml
<!-- language-all: lang-html -->
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - AWC Web Console</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
</head>
Index.cshtml markup with validation JS applied in Doc ready function
<script type="text/javascript">
$(document).ready(function () {
alert("doc ready");
// JQuery client validation
$("#prodIdFilterForm").validate(
{
onsubmit: true,
rules: {
productId_str: {required: true, minlength: 10, number:true }
},
messages: { productId_str: "product Id must be entered" },
// Force validation when control looses focus
onfocusout: function (element) {
alert("onfocusout"); // not entering this block !
$("#productId_str").removeAttr('style');
$("#productId_str").valid(); // fire validation
$(element).valid();
}
,
showErrors: function (errorMap, errorList)
{
if (errorList.length > 0)
{
for (var i = 0; i < errorList.length; i++)
{
$("#" + errorList[i].element.id).css({ 'background-color': '#FFDFDF' });
}
}
}
}
);
}); // DocReady
</script>
Body of form markup
@{
ViewBag.Title = "Messages";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using ( Html.BeginForm("SelectProduct", "WMSMessages", Model, FormMethod.Post, new { @id = "prodIdFilterForm"} ) )
{
<fieldset class="filtering">
<legend>SelectExtensions Product</legend>
<div>
<b>Product Id:</b>
@Html.TextBoxFor(model => model.productId_str, new { @id ="productId_str"} )
<div class="filterSubmitBox">
<input type="submit" value="Show Messages" />
</div>
</div>
</fieldset>
}