不显眼的验证 - 添加的规则仅在现有字段到位时有效

时间:2015-04-29 16:25:22

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

我正在尝试将所需规则动态添加到单选按钮列表中。

以下示例适用于'姓名'行被删除验证现在更长时间火了。

似乎需要在页面上有一个带有data-val属性的字段,以便验证插件开始观看表单。

如何向没有现有不显眼字段的页面添加动态规则?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>

<div class="container body-content">
    <form action="" method="post">

        <!-- When below row is commented out validation no longer fires -->
        <div class="row">
            <div class="col-md-4">
                <p>Name</p>
            </div>
            <div class="col-md-4">
                <input class="input-validation-error" data-val="true" data-val-required="Name required" id="Name" name="Name" type="text" value=""/>
            </div>
            <div class="col-md-4">
                <span class="field-validation-error" data-valmsg-for="Name" data-valmsg-replace="true"></span>
            </div>
        </div>

        <div class="row dynamic_checkbox_container">
            <div class="col-md-4">
                <p>Dynamic Checkbox</p>
            </div>
            <div class="col-md-2">
                Yes
                <input id="CheckBox" name="CheckBox" type="radio" value="True"/>
            </div>
            <div class="col-md-2">
                No
                <input id="CheckBox" name="CheckBox" type="radio" value="False"/>
            </div>
            <div class="col-md-4">
                <span class="field-validation-valid" data-valmsg-for="CheckBox" data-valmsg-replace="true"></span>
            </div>
        </div>


        <input type="submit" value="Go" name="go"/>
    </form>
</div>

    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2/jquery.validate.unobtrusive.js"></script>
<script>

    $(document).ready(function() {


        $(".dynamic_checkbox_container input").each(function() {

            $(this).rules("add", {
                required: true,
                messages: {
                    required: "This field is required."
                }
            });
        });
    });

</script>
</body>
</html>

0 个答案:

没有答案