繁体   English   中英

jQuery / MVC条件验证

[英]jQuery/MVC conditional validation

在以下情况下,我无法使用jQuery验证文本框。 我有3套名字,姓氏和位置输入框。

当提供名字或姓氏或两者都提供时,我也需要使“位置”输入框为必填项,但这仅适用于该集合。

如果其他2组名字和姓氏为空,则我不想将位置输入框设为必填项。

请告知我如何使用jQuery客户端验证来实现。

<div id="divNamesAndLocation" style="display: none;">
    @for (int i = 0; i < 3; i++)
    {
        <div class="row">
            <div class="col-sm-4 form-group">
                @Html.LabelFor(x => x.NamesAndLocation[i].FirstName)
                @Html.ValidationMessageFor(x => x.NamesAndLocation[i].FirstName)
                @Html.TextBoxFor(x => x.NamesAndLocation[i].FirstName)
            </div>
            <div class="col-sm-4 form-group">
                @Html.LabelFor(x => x.NamesAndLocation[i].LastName)
                @Html.ValidationMessageFor(x => x.NamesAndLocation[i].LastName)
                @Html.TextBoxFor(x => x.NamesAndLocation[i].LastName)
            </div>
            <div class="col-sm-4 form-group">
                @Html.LabelFor(x => x.NamesAndLocation[i].Location)
                @Html.ValidationMessageFor(x => x.NamesAndLocation[i].Location)
                @Html.TextBoxFor(x => x.NamesAndLocation[i].Location)
            </div>
        </div>
    }
</div>  

这是使用jquery验证的方法。 请尝试使用您的引导程序。 我知道这可行,因为我已经对其进行了测试。 这是控制器:

public class NamesAndLocation
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Location { get; set; }
}

public class NamesAndLocationList
{
    public IList<NamesAndLocation> NamesAndLocation { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index10()  //this Method name can change
    {
        NamesAndLocationList list = new NamesAndLocationList();
        list.NamesAndLocation = new List<NamesAndLocation>();
        list.NamesAndLocation.Add(new NamesAndLocation { FirstName = "fn1", LastName = "ln1", Location = "loc1" });
        list.NamesAndLocation.Add(new NamesAndLocation { FirstName = "fn2", LastName = "ln2", Location = "loc2" });
        list.NamesAndLocation.Add(new NamesAndLocation { FirstName = "fn3", LastName = "ln3", Location = "loc3" });

        return View(list);
    }

这是视图:

@model Testy20161006.Controllers.NamesAndLocationList
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index10</title>
    <script src="https://code.jquery.com/jquery-1.7.1.min.js"
            integrity="sha256-iBcUE/x23aI6syuqF7EeT/+JFBxjPs5zeFJEXxumwb0="
            crossorigin="anonymous"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script>
        $.validator.setDefaults({
            submitHandler: function () {
                alert("submitted!");
            }
        });
        $().ready(function () {
            $("#signupForm").validate({
                rules: {
                    location0:
                        {
                            required: function (element) {
                                var mybool = $("#fname0").val() == "" || $("#lname0").val() == ""
                                return mybool;
                            }
                        },
                    location1:
                        {
                            required: function (element) {
                                var mybool = $("#fname1").val() == "" || $("#lname1").val() == ""
                                return mybool;
                            }
                        },
                    location2:
                        {
                            required: function (element) {
                                var mybool = $("#fname2").val() == "" || $("#lname2").val() == ""
                                return mybool;
                            }
                        }
                },
                messages: {
                    location0: "Please add location1",
                    location1: "Please add location2",
                    location2: "Please add location3"
                }
            });
        });
    </script>
</head>
<body>
    @using (Html.BeginForm("", "", FormMethod.Get, new { id = "signupForm" }))
    {
        for (int i = 0; i < 3; i++)
        {
            <div class="row">
                <div class="col-sm-4 form-group">
                    @*we have Name and name attributes, but Name is parsed first*@
                    @Html.LabelFor(x => x.NamesAndLocation[i].FirstName)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].FirstName)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].FirstName, new { id = "fname" + i.ToString(), Name = "fname" + i.ToString() })
                </div>
                <div class="col-sm-4 form-group">
                    @Html.LabelFor(x => x.NamesAndLocation[i].LastName)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].LastName)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].LastName, new { id = "lname" + i.ToString(), Name = "lname" + i.ToString() })
                </div>
                <div class="col-sm-4 form-group">
                    @Html.LabelFor(x => x.NamesAndLocation[i].Location)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].Location)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].Location, new { id = "location" + i.ToString(), Name = "location" + i.ToString() })
                </div>
            </div>
        }
        <input type="submit" value="submit" />
    }
</body>
</html>

这将适用于div:

@model Testy20161006.Controllers.NamesAndLocationList
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index10</title>
    <script src="https://code.jquery.com/jquery-1.7.1.min.js"
            integrity="sha256-iBcUE/x23aI6syuqF7EeT/+JFBxjPs5zeFJEXxumwb0="
            crossorigin="anonymous"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script>
        $.validator.setDefaults({
            submitHandler: function () {
                alert("submitted!");
            }
        });
        $().ready(function () {
            //this is on the click event, but you can put it outside of onclick for on page load
            $("#btnClick").click(function (event) {
                $("#divlocationmsgtouser1").val("");
                $("#divlocationmsgtouser2").val("");
                $("#divlocationmsgtouser3").val("");

                //COPY FROM HERE FOR OTHER ROWS
                if (!$("#divfname0").length || !$("#divlname0").length)
                {
                    alert("fname or lname row one div does not exist")
                    if (!$("#divlocation0").length) {
                        alert("location row one div needs to exist as fname and/or lname row one div does not-will not submit")
                        $("#divlocationmsgtouser1").text("Location row One div does not exist and fname and/or lname row One does not exist");
                        event.preventDefault();
                    }
                }
                else
                {
                    alert("first and last name row one div exists, so it doesn't matter if location row one div exists")

                }
                //END COPY

            });

        });
    </script>
</head>
<body>
    @using (Html.BeginForm("Index10", "Home", FormMethod.Post, new { id = "signupForm" }))
    {
        for (int i = 0; i < 3; i++)
        {
            //credit to http://stackoverflow.com/questions/21322639/asp-net-mvc-razor-foreach-loop-adding-id-to-div
            <div class="row">
                @*!CHANGE the div name below from divfname to divfnameNADA AND change the divlocation to divlocationNADA to see NOT POSTING*@
                <div class="col-sm-4 form-group" id="@string.Format("divfnameNADA{0}",i)">
                    @*we have Name and name attributes, but Name is parsed first*@
                    @Html.LabelFor(x => x.NamesAndLocation[i].FirstName)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].FirstName)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].FirstName, new { id = "fname" + i.ToString(), Name = "fname" + i.ToString() })
                </div>
                <div class="col-sm-4 form-group" id="@string.Format("divlname{0}",i)">
                    @Html.LabelFor(x => x.NamesAndLocation[i].LastName)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].LastName)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].LastName, new { id = "lname" + i.ToString(), Name = "lname" + i.ToString() })
                </div>
                <div class="col-sm-4 form-group" id="@string.Format("divlocationNADA{0}",i)">
                    @Html.LabelFor(x => x.NamesAndLocation[i].Location)
                    @Html.ValidationMessageFor(x => x.NamesAndLocation[i].Location)
                    @Html.TextBoxFor(x => x.NamesAndLocation[i].Location, new { id = "location" + i.ToString(), Name = "location" + i.ToString() })
                </div>
            </div>
        }
        <div id="divlocationmsgtouser1"></div>
        <div id="divlocationmsgtouser2"></div>
        <div id="divlocationmsgtouser3"></div>
        <input type="submit" value="submit" id="btnClick" />
    }
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM