不显眼的验证不验证表单上的一个字段

时间:2016-02-15 21:48:28

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

所以我有一个由razor创建的字段列表,但字段PhoneNumber未被验证。奇怪的是,如果我将字段置于第一个if语句的外部,则验证将正常工作。除此之外,其他两个字段都验证良好,它只是PhoneNumber

@if (Model?.CompanyContactList != null)
{
    if (Model.CompanyContactList.Count != 0)
    {
        for (int i = 0; i < Model.CompanyContactList.Count; i++)
        {
            @Html.EditorFor(a => a.CompanyContactList[i].PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(a => a.CompanyContactList[i].PhoneNumber, "", new { @class = "text-danger" })

            @Html.EditorFor(a => a.CompanyContactList[i].Name, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(a => a.CompanyContactList[i].Name, "", new {@class = "text-danger"})

            @Html.EditorFor(a => a.CompanyContactList[i].Email, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(a => a.CompanyContactList[i].Email, "", new {@class = "text-danger"})
        }
    }
}

PhoneMumber的ViewModel

[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\+?[0-9]{3}-?[0-9]{6,12}$", ErrorMessage = "This must be a vaild phone number")]
[MaxLength(16, ErrorMessage = "Your Phone number must be less than 15 numbers")]
[Display(Name = "Phone Number Mobile")]
public string PhoneNumber { get; set; }

以HTML格式呈现的字段

<input class="form-control text-box single-line" data-val="true" 
data-val-maxlength="Your Phone number must be less than 15 numbers" data-val-maxlength-max="16" 
data-val-phone="The Phone Number Mobile field is not a valid phone 
number." data-val-regex="This must be a vaild phone number" data-val-regex-
pattern="^\+?[0-9]{3}-?[0-9]{6,12}$" id="CompanyContactList_0__PhoneNumber" 
name="CompanyContactList[0].PhoneNumber" type="tel" value="22222222222">

<span class="field-validation-valid text-danger" 
data-valmsg-for="CompanyContactList[0].PhoneNumber" data-valmsg-replace="true"></span>

引用的JS文件(在页面的头部)

<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>

为什么这个领域不会验证的任何想法?

0 个答案:

没有答案