首页 > 解决方案 > 使用“MaxLength”DataAnnotations 属性时如何删除“maxlength”html 属性?

问题描述

我最近将我的 Web 应用程序从 .NET Core 2.1 升级到了 Core 3.1。

注意到 Max Length 的不显眼验证不像以前那样工作。将 html 属性maxlength添加到输入元素。因此,用户只能在输入字段中输入最大设置的字符数。没有消息通知用户他们已超出该特定字段的最大字符限制。

如何通知用户他们已达到/超过限制?

我的代码:

AddSpirit.cshtml

@model WebApp.ViewModels.SpiritViewModel

<div class="container pt-5">
    <div class="row">
        <div class="col-12">
            <form asp-action="AddSpirit" method="POST">
                <fieldset class="form-group">
                    <label asp-for="Name"></label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-danger"></span>
                </fieldset>
                <fieldset class="form-group">
                    <label asp-for="Price"></label>
                    <input asp-for="Price" class="form-control" />
                </fieldset>
                <fieldset class="form-group">
                    <label asp-for="Stock"></label>
                    <input asp-for="Stock" class="form-control" />
                </fieldset>

                <button type="submit" class="btn btn-sm btn-danger text-uppercase py-2 px-3 px-md-3 mb-2">  
                    Save Changes    
                </button>   
            </form>
        </div>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

SpiritViewModel.cs

using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

namespace WebApp.ViewModels
{
    public class SpiritViewModel
    {
        [JsonProperty("name")]
        [MaxLength(5, ErrorMessage = "{0} should not be longer than {1} characters")]
        [MinLength(2, ErrorMessage = "{0} should be longer than {1} characters")]
        public string Name { get; set; }

        [JsonProperty("price")]
        [Required(ErrorMessage = "Enter the spirit's price.")]
        [Range(10, 500, ErrorMessage = "Accepting only spirits in price range INR 10 - 500")]
        public double Price { get; set; }

        [JsonProperty("stock")]
        public int Stock { get; set; }

    }
}

标签: asp.net-coreasp.net-core-3.1unobtrusive-validation

解决方案


在 cshtml 中设置maxlengthminlength属性值将是一种停止 MaxLength 或 StringLength DataAnnotations 限制输入字段中字符的方法。一旦用户能够输入更多字符,不显眼的验证就可以正常工作。

<input asp-for="Name" maxlength="" minlength="" class="form-control" />

推荐阅读