I have a HTML form that uses unobtrusive validation in my website which is an ASP.Net MVC4 application. The form from my view is simple and is shown below
@Using (Html.BeginForm())
{
@: Listing for @ViewBag.itemNumber
@Html.TextBoxFor(model=>model.Name)
@Html.TextBoxFor(model=>model.Location)
@:<input type="submit" value="Save" />
}
My controller is as shown below
public ActionResult test()
{
string itemNumber = Request.params["item"];
ViewBag.itemNumber = itemNumber;
return View();
}
and my model is
public class item
{
[StringLength(10, ErrorMessage = "The Name should be atleast 3 characters in length", MinimumLength = 3)]
public string Name {get;set;}
public string Location {get;set;}
}
The problem I am having is that the unobtrusive validation kicks in as soon as the page loads even before my first form submit. The textbox for Name turns red as soon as I start typing because of the minimum length validation. I have used unobtrusive validation successfully and without this issue on other pages of the same website. I suspect that the validation is kicking in early on this particular page because of the code in my controller which retrieves a value from the URL GET parameters and sets it in the Viewbag. Is my assumption correct? If it is, how can I prevent the validation from starting too early on this page?
EDIT: I have the following javascript libraries on my page in the same order as specified below
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.9.0.min.js" type="text/javascript"></script>
<script src="~/Scripts/jQuery.tmpl.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
The one you described is the default behaviour! Fields are validated also onKeyUp as default. This doesn happens with required fields simply because when the key is up the textbox is not empty anymore! So maybe you are confused with the behaviour of the required field case.
Anyway you can disable the keyUp validation. See here the full options of the plugin you can change : http://docs.jquery.com/Plugins/Validation/validate#toptions