简体   繁体   English

如何将验证字段长度添加到@Html.ValidationMessageFor 客户端验证消息?

[英]How to add validated field length to @Html.ValidationMessageFor client validation message?

I have a "Description" TextArea field on my form.我的表单上有一个“描述”文本区域字段。

@Html.ValidationMessageFor(m => m.Opis, "", new { @class = "control-label text-danger" })

Model property has following attributes: Model 属性具有以下属性:

[Display(Name = nameof(Global.Opis), ResourceType = typeof(Global))]
[Required]
[MaxLength(500)]
public string Opis { get; set; }

It renders as the following html:它呈现为以下 html:

<textarea class="form-control input-validation-error" cols="20" data-val="true" data-val-length="Pole Opis musi być ciągiem o maksymalnej długości 500." data-val-length-max="500" data-val-required="[Opis]: Pole musi być wypełnione." id="Opis" name="Opis" rows="5" aria-describedby="Opis-error" aria-invalid="true"></textarea>
<span class="control-label text-danger field-validation-error" data-valmsg-for="Opis" data-valmsg-replace="true"><span id="Opis-error" class="">[Opis]: Pole musi być wypełnione.</span></span>

It validates fine however I want to change the client-side message template for it to show also the current length of the Description field.它验证得很好,但是我想更改客户端消息模板以显示描述字段的当前长度。 Something like:就像是:

Maximum length of Description field is 500. You've entered 510 characters.描述字段的最大长度为 500。您已输入 510 个字符。

I've tried to add a custom attribute derived from MaxLengthAttribute however it seems like this solution is only for server-side validation as the debugger doesn't hit the IsValid method.我尝试添加一个从 MaxLengthAttribute 派生的自定义属性,但似乎此解决方案仅用于服务器端验证,因为调试器没有命中 IsValid 方法。

public class MaxLengthWithLengthMessageAttribute : MaxLengthAttribute
    {
        public MaxLengthWithLengthMessageAttribute(int maximumLength) : base(maximumLength)
        {
        }

        public override bool IsValid(object value)
        {
            string input = Convert.ToString(value);

            if (input.Length > base.Length)
                base.ErrorMessage =
                    $"Pole może zawierać maksymalny ciąg {base.ErrorMessage} znaków. Wprowadzono {input.Length} znaków.";

            return base.IsValid(value);
        }
    }


    public class MaxLengthWithLengthMessageValidator : DataAnnotationsModelValidator
    {
        private string _errorMessage = "Pole może zawierać maksymalny ciąg #1 znaków. Wprowadzono #2 znaków.";
        private MaxLengthWithLengthMessageAttribute _attribute;

        public MaxLengthWithLengthMessageValidator(ModelMetadata metadata, ControllerContext context, MaxLengthWithLengthMessageAttribute attribute) : base(metadata, context, attribute)
        {
            _attribute = attribute;
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this._errorMessage,
                ValidationType = "maxlength"
            };
            rule.ValidationParameters.Add("max", _attribute.Length);
            yield return rule;
        }
    }

How do you go about it?你是怎么想的呢?

You can customize StringLengthAttribute Class like below您可以自定义StringLengthAttribute Class ,如下所示

public class MyStringLengthAttribute : StringLengthAttribute
{
public MyStringLengthAttribute(int maximumLength)
    : base(maximumLength)
{
}

public override bool IsValid(object value)
{
    string val = Convert.ToString(value);
    
    if (val.Length > base.MaximumLength)
        base.ErrorMessage = String.Format("Maximum length of Description field is {0}. You've entered {1} characters.",base.MaximumLength,val.Length);
    return base.IsValid(value);
}
}

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

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