asp.net-core - 使用“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; }
}
}
解决方案
在 cshtml 中设置maxlength和minlength属性值将是一种停止 MaxLength 或 StringLength DataAnnotations 限制输入字段中字符的方法。一旦用户能够输入更多字符,不显眼的验证就可以正常工作。
<input asp-for="Name" maxlength="" minlength="" class="form-control" />
推荐阅读
- unit-testing - 如何在测试时使 Spring boot webflux 在默认 Netty 而不是 Jetty 上启动
- node.js - 是否可以推送文本以提示输入?
- google-cloud-dataflow - 如何通过 gcloud CLI 激活 Dataflow Shuffle 服务
- java - 部分反序列化响应为空
- javascript - 我可以防止 IDE 通过 TSLint 或 tsconfig 自动包装属性吗?
- c# - 检查页面上是否存在元素的最佳方法是什么?
- config - 为 INFOMAKER 加密、保护 .ini 文件
- json - 应该如何看起来像嵌入了其他表单的 json 表单
- node.js - 如何使用nodejs在mongodb中上传多个文件
- list - 'TableList' 对象没有属性 'to_excel'