添加动态字段到表单 - 验证什么?

时间:2014-09-16 08:58:59

标签: asp.net-mvc

我有一个表单,用户可以动态地将字段'Name'添加到我的表单中,我使用knockoutjs动态添加字段 - 但在这种情况下验证工作错误 - 例如,如果我不填写需要'Name'许多“名称”字段中的一个然后我在每个字段上看到验证消息:

enter image description here

我认为knockoutjs在这种情况下可以帮助我,但它只能动态添加字段。现在我在我的模型中使用验证属性:

public class Person
{
    [Required(ErrorMessage = "Name is required")]
    [StringLength(50, MinimumLength = 2)]
    public string Name { get; set; }
}

如果我动态添加字段,是否应该在javascriptin中添加单独的验证?

这是我对knockoutjs的看法:

@model Knockout.Models.Person

@using (Html.BeginForm()) 
{    
    <div class="form-horizontal">
        <!-- ko foreach: positions -->
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Name, new { data_bind = "value: name" })
                    @Html.ValidationMessageFor(model => model.Name)
                </div>
            </div>
        <!-- /ko -->

        <button data-bind="click: addPosition">Add one</button>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<script>
    $(document).ready(function () {
        var viewModel = createViewModel();
        ko.applyBindings(viewModel);
    });

    function createViewModel() {
        var createPosition = function () {
            return {
                name: ko.observable()
            };
        };

        var addPosition = function () {
            positions.push(createPosition());
        };

        var positions = ko.observableArray([createPosition()]);

        return {
            positions: positions,
            addPosition: addPosition
        };
    }
</script>

1 个答案:

答案 0 :(得分:0)

使用此函数将必需的字段验证添加到动态创建的控件

将元素id传递给函数 e.g。

setRequiredFieldValidation('#YourCreatedElementID')

功能

function setRequiredFieldValidation(element) {
    var $PropElement = $(element).filter(':not(:hidden)');
    if ($PropElement.length > 0 && $PropElement[0].getAttribute('data-val-required') == null) {
        var $label = $('label[for=\'' + $PropElement[0].id + '\']');
        if ($label.length > 0) {
            $label.prepend('<span class=\'mandatory\' >*</span>') ///For ADA Compliance... To add the asterix before the required element...
            var errorMessage = "";
            if ($PropElement.attr("val-label-text"))
                errorMessage =  $PropElement.attr("val-label-text") + " is required.";
            else
                errorMessage = $label.text().replace(/^\*/, '') + " is required.";
            $PropElement.attr('data-val-required', errorMessage); ///To set the error message and add the JQuery UnObtrusive Required field validation...
            ///This is for adding the data-val attribute to the dynamically created required fields...
            if (!$PropElement.attr('data-val')) {
                $PropElement.attr('data-val', true);
            }
        }
    }
}