C# 如何防止用户在ASP.NET Core MVC的文本框中添加超过两位小数

C# 如何防止用户在ASP.NET Core MVC的文本框中添加超过两位小数,c#,razor,asp.net-core-mvc,decimal,viewmodel,C#,Razor,Asp.net Core Mvc,Decimal,Viewmodel,有没有一种方法不允许用户在视图文本框中添加两个以上的小数?当限制字符串时,我想要类似于[StringLength(5)]的东西,但需要小数 在我当前的viewmodel中: [Required(ErrorMessage = "Select the model of the vehicle you wish to sell")] [Display(Name = "Price")] public decimal? Price { get; set; } 我认

有没有一种方法不允许用户在视图文本框中添加两个以上的小数?当限制字符串时,我想要类似于
[StringLength(5)]
的东西,但需要小数

在我当前的viewmodel中:

[Required(ErrorMessage = "Select the model of the vehicle you wish to sell")]
[Display(Name = "Price")]
public decimal? Price { get; set; }
我认为:

<div class="form-group col-md-4">
        @Html.LabelFor(model => model.Price) <span class="req">*</span>
        @Html.TextBoxFor(model => model.Price, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Price, "", new { @class = "req" })
</div>

@LabelFor(model=>model.Price)*
@Html.TextBoxFor(model=>model.Price,新的{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Price,“,new{@class=“req”})
目前,在文本框中,用户可以输入10.000000。我不想让用户输入超过10.00

我在这个网站和其他网站上尝试了许多不同的资源,但没有一个有效。我将感谢任何帮助或其他论坛的链接

有没有一种方法不允许用户在视图文本框中添加两个以上的小数

为了达到要求,您可以尝试使用
RegularExpression
属性来验证数据的格式

[RegularExpression(@"^[0-9]+(\.[0-9]{1,2})$")]
若启用了客户端验证,则当用户输入未验证时,上述解决方案将显示错误消息

此外,如果您只是想防止用户输入超过2位小数,而不是显示客户端错误消息,您可以尝试使用一些jQuery输入掩码,如下所示

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script>
    $("#Price").mask('00.00', { reverse: true });
</script> 

$(“#Price”).mask('00.00',{反向:true});

这是否回答了您的问题@马丁:不完全是。如果用户使用两个以上的小数,则只会发出错误消息。我希望它首先阻止用户输入两个以上。就像[StringLength(5)]不允许用户在字符串中键入超过5个字符一样,请注意您的web应用程序不会为世界其他国家(例如法国或德国)的用户中断,这些国家使用逗号
表示小数点,点
表示千位分隔符。这对法国或德国的用户不起作用,顺便说一句,2020年我们不应该再使用jQuery了。考虑使用JavaScript内置的 ItL./Cord>库:是的,对于非英语区域,使用逗号(“”)用于小数点。