使用掩码插件时,Jquery验证停止为输入工作

时间:2014-05-23 18:55:17

标签: asp.net-mvc jquery-validate unobtrusive-validation masking

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        TestModel model = new TestModel();
         return View(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;}
}

查看

<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小提琴 https://dotnetfiddle.net/qndNxE

问题

如果对掩码插件的两次调用被注释掉,则验证工作正常。这意味着如果我:

  1. 在名字和姓氏文本框中输入内容,然后输入
  2. 选中每个框并退回并点击删除以清除 内容
  3. 验证消息显示告诉我这些字段是必需的。

    如果我取消注释两个对掩码插件的调用并重复上述两个步骤,则其中一个文本框(第一个或最后一个)将不会显示其验证消息。

    任何人都可以告诉我为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我无法找到原因,但我最终做了什么,直到我们能够获得更好的库情况来解决问题的方法是处理表单输入的输入事件并将其标记为脏并验证它们是否有效他们是:

$("#myForm input").on("input", function () {
    $("#myForm").data("validator").element(this);
});