jQuery验证多个必填字段

时间:2018-08-02 13:36:48

标签: jquery asp.net-mvc jquery-validate

我有一个带有几个必填字段的表格。问题是,当我在填写第一个字段后将焦点移到下一个字段时,我收到即时验证错误,指出第二个字段是必需的。我刚进入第二个。

我在这样的模型上使用验证属性:

public class SampleModel : BaseModel
{
    [Required]
    [Display(Name = "First name")]
    [RegularExpression(@"^[a-zA-Z]*$", ErrorMessage = "First name must be letters only")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Second name")]
    [RegularExpression(@"^[a-zA-Z]*$", ErrorMessage = "Second name must be letters only")]
    public string SecondName { get; set; }
}

然后cshtml看起来像(摘录):

    <fieldset style="background-color: #e0e3e6; border-radius:6px; color:black;">
        <div class="form-group">
            <div class="form-inline">
                <div class="form-group">
                    @Html.LabelFor(m => m.FirstName, string.Format("{0}:", Html.DisplayNameFor(m => m.FirstName)))
                    @Html.TextBoxFor(m => m.FirstName, new { autofocus = "autofocus", maxlength = "20", style = "width:152px;" })
                </div>
                <div class="form-group">
                    @Html.LabelFor(m => m.SecondName, string.Format("{0}:", Html.DisplayNameFor(m => m.SecondName)))
                    @Html.TextBoxFor(m => m.SecondName, new { autofocus = "", maxlength = "20" })
                </div>
            </div>
        </div>

        <div class="search-button">
            <input id="btnSubmit" type="submit" class="btn2" value="Search" />
        </div>

        <div id="val-summary" class="field-validation-error">
            @Html.ValidationSummary(true)
        </div>

        @Html.ValidationMessageFor(m => m.FirstName)
        @Html.ValidationMessageFor(m => m.SecondName)
    </fieldset>

我有什么办法可以防止这种行为?例如。输入焦点后不验证字段?优选地,仅当焦点超出验证输入集的范围时。还是提交时?

我正在使用: * jQuery验证插件1.11.1

谢谢Radek

0 个答案:

没有答案