使用IValidatableObject

时间:2019-04-11 11:59:18

标签: validation asp.net-core asp.net-core-2.0

我有一个带有2个按钮(取消和提交)和TextArea的简单表单。用户键入电子邮件地址列表,然后按提交。我试图弄清楚为什么在提交表单时未显示我的自定义消息。我知道验证逻辑会触发我的[Required]规则,因此可以看到错误消息:

enter image description here

但是,当我输入“ test @”之类的数据然后提交时,会触发 Validate 中的逻辑,但是我看不到错误消息“ 请确保所有电子邮件都是有效的”。谁能指出我做错了什么。

那是我的模特:

public class ShareModel : IValidatableObject
{
    [HiddenInput] public string Title { get; set; }

    [Required]
    public string Emails { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // custom validation logic here
        yield return new ValidationResult($"Please make sure that all of the emails are valid", new[] { "Emails" });
    }
}

这是我的观点:

<div class="modal fade" id="shareFormModal" role="dialog">
<div class="modal-dialog modal-md">
    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Share Workbook - @Model.Title</h4>

        </div>

        @using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post, new {@id = "partialform"}))
        {
            <div class="modal-body">

                <label>@BaseLanguage.Share_workbook_Instruction_text</label>
                <div class="form-group">
                    <textarea class="form-control" asp-for="Emails" rows="4" cols="50" placeholder="@BaseLanguage.ShareDialogPlaceholder"></textarea>
                    <span asp-validation-for="Emails" class="text-danger"></span>
                </div>

                <input asp-for="Title"/>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">Share</button>
                <button id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        }

    </div>
</div>

2 个答案:

答案 0 :(得分:1)

根据此post IValidatableObject不在客户端考虑。为了显示来自自定义验证的自定义错误消息,您需要实现自定义ValidationAttribute,它也实现了here所述的IClientModelValidator接口。

答案 1 :(得分:0)

为了将来参考,正如亚历山大在上面解释的那样,我必须同时使用ValidationAttribute, IClientModelValidator

ShareModel

public class ShareModel
{
    [HiddenInput] public string Title { get; set; }

    [Required]
    [IsEmailAttribute(ErrorMessage = "Check all of the emails you have typed")]
    public string Emails { get; set; }
}

public class IsEmailAttribute : ValidationAttribute, IClientModelValidator
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
         return new ValidationResult("Check emails!");
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val-isEmail", errorMessage);
    }

    private bool MergeAttribute(
        IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }

}

_ShareView.cshtml

@using DNAAnalysisCore.Resources
@model DNAAnalysisCore.Models.ShareModel

<!-- Modal -->
<div class="modal fade" id="shareFormModal" role="dialog">
    <div class="modal-dialog modal-md">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Share Workbook - @Model.Title</h4>

            </div>

            @using (Html.BeginForm("ShareWorkbook", "Home", FormMethod.Post, new {@id = "partialform"}))
            {
                <div class="modal-body">

                    <label>@BaseLanguage.Share_workbook_Instruction_text</label>
                    <div class="form-group">
                        <textarea class="form-control" asp-for="Emails" rows="4" cols="50" placeholder="@BaseLanguage.ShareDialogPlaceholder"></textarea>
                        <span asp-validation-for="Emails" class="text-danger"></span>
                    </div>

                    <input asp-for="Title"/>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Share</button>
                    <button id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                </div>
            }

        </div>
    </div>
</div>

index.cshtnl

@using DNAAnalysisCore.Resources
@model DNAAnalysisCore.Models.WorkBookModel
@{
}

@section BodyFill
{
    <div id="shareFormContainer">
        <!--PLACEHOLDER FOR SHARE DIALOG -->
        @{
            @Html.Partial("_ShareView", new ShareModel())
        }

    </div>

    <div class="workbook-container">
        <table class="table">
            <tbody>
                @foreach (var workbook in Model.Workbooks)
                {
                    <tr>
                        <td>@Html.ActionLink(workbook.Name, "Open", "OpenAnalytics", new { id = Model.Id, workbook = workbook.Name })</td>
                        <td>
                            <button title="Share" class="share-button" onclick='showSharingView("@workbook.Name")'>&nbsp;</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

@section Scripts
{
    <!--Load JQuery 'unobtrusive' validation -->
    @await Html.PartialAsync("_ValidationScriptsPartial")
    <script type="text/javascript">

        function showSharingView(title) {
            var url = "@Url.Action("ShowShareDialog", "Home")" + "?workbookTitle=" + encodeURI(title);
            $('#shareFormContainer').load(url,
                function() {
                    $('#shareFormModal').modal("show");
//                    // We need to manually register the form for validation as the dialog is
//                    // not included in the page when it initially loads
                    $.validator.unobtrusive.parse("#partialform");

                    // email validation
                    $.validator.addMethod("isEmail",
                        function (value, element, parameters) {
                            // TODO CLIENT SIDE VALIDATETION LOGIC HERE
                            return false;
                        });
                    $.validator.unobtrusive.adapters.add("isEmail",
                        [],
                        function(options) {
                            options.rules.isEmail = {};
                            options.messages["isEmail"] = options.message;
                        });
                });
        }

    </script>
}