首页 > 解决方案 > .Net Core 中的自定义属性未显示验证消息

问题描述

我正在为验证创建自定义属性以覆盖 .Net Core 中的 RegularExpressionAttribute,并为客户端验证实现了 IClientModelValidator。验证适用于字段,但未显示错误消息。ModelState.IsValid 也给出了 Invalid 该字段,但未显示验证消息。

视图模型

[Required]
[Display(Name = "First Name")]
[RestrictSplCharacters]
public string FirstName { get; set; }

覆盖属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class RestrictSplCharactersAttribute : RegularExpressionAttribute, IClientModelValidator
{
   private string errorMessage= "Special characters or blank space is not allowed in {0}";

public RestrictSplCharactersAttribute()
    : base(@"[_A-z0-9]*((-|\s)*[_A-z0-9])*$")
{
    this.ErrorMessage = this.errorMessage;
}

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

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

在 Html Control 中就像

<div class="oneditshow">
<input autocomplete="off" class="k-textbox valid k-valid" data-val="true" data-val-required="The First Name field is required." data-val-restrictSplCharacters="Special characters or blank space is not allowed in First Name" id="FirstName" name="FirstName" placeholder="First Name" required="required" style="width: 100%" value="" aria-required="true" aria-describedby="FirstName-error">
<span class="text-danger field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true" style="display: none;"></span>
   </div>

Javascript函数

<script>

    var $jQval = $.validator;

    $jQval.addMethod("restrictSplCharacters",
        function (value, element, parameters) {
            var regExp = "/[_A-z0-9]*((-|\s)*[_A-z0-9])*$/";
            if (value.match(regExp)) {
                return true;
            } else {
                return false;
            }
        });
    var adapters = $jQval.unobtrusive.adapters;
    adapters.addBool("restrictSplCharacters");
</script>

标签: javascript.net-coredata-annotations

解决方案


谢谢,客户端验证不会被触发,因为它是剑道 UI。我用下面的 javascript 替换我的 JavaScript 以获得剑道自定义验证规则。

    //register custom validation rules
(function ($, kendo) {
    $.extend(true, kendo.ui.validator, {
        rules: { // custom rules
            restrictSpecialCharacters: function (input, params) {
                //check for the rule attribute 
                if (input.filter("[data-val-restrictSpecialCharacters]").length && input.val()) {
                    return /[_A-z0-9]*((-|\s)*[_A-z0-9])*$/.test(input.val());
                }
                return true;
            }
        },
        messages: { //custom rules messages
            restrictSpecialCharacters: function (input) {
                // return the message text
                return input.attr("data-val-restrictSpecialCharacters");
            }
        }
    });
})(jQuery, kendo);

推荐阅读