Controller
public class HomeController : Controller
{
public ActionResult Index()
{
TestModel model = new TestModel();
return View(model);
}
}
Model
public class TestModel
{
[Required(ErrorMessage="You have to put a first name!")]
[StringLength(maximumLength: 24)]
[Display(Name="First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Yo the last name is required!")]
[StringLength(maximumLength: 24)]
public string LastName { get; set; }
[Required]
public string PhoneNumber { get; set; }
[Required]
public string ZipCode {get; set;}
}
View
<h2>Test</h2>
@using(Html.BeginForm())
{
@Html.LabelFor(model => model.FirstName)
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
<br />
@Html.LabelFor(model => model.LastName)
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
<br />
@Html.LabelFor(model => model.PhoneNumber)
@Html.TextBoxFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
<br />
@Html.LabelFor(model => model.ZipCode)
@Html.TextBoxFor(model => model.ZipCode)
@Html.ValidationMessageFor(model => model.ZipCode)
<br />
<input type="submit"/>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
// Masked plugin script here, linking to site doesn't work
</script>
<script type="text/javascript">
$(document).ready(function () {
// Validation works when masks are commented out
$("#PhoneNumber").mask("(999) 999-9999");
$("#ZipCode").mask("99999");
});
</script>
.Net Fiddle https://dotnetfiddle.net/qndNxE
Problem
If the two calls to the mask plugin are commented out validation works fine. This means that if I:
- Enter something into the first name and last name text boxes and then
- Tab out of each box and back in and hit delete to clear the contents
Validation messages appear telling me that the fields are required.
If I uncomment out the two calls to the mask plugin and repeat the two steps above, one of the textboxes (first or last) will not display its validation message.
Can anyone tell me why this happens and what to do to get around it?