问题描述
我最近将我的 Web 应用程序从 .NET Core 2.1 升级到 Core 3.1。
注意到 Max Length 的不显眼验证不像以前那样工作。 html 属性 maxlength 被添加到 input 元素。因此,用户只能在输入字段中输入最大设置的字符数。没有消息通知用户他们已超过该特定字段的最大字符数限制。
我的代码:
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" />