[英]Why validation for Decimal not work for ASP.NET Core 3.1 Razor Pages?
Why validation for Decimal not work for ASP.NET Core 3.1 Razor Pages ?为什么 Decimal 的验证不适用于 ASP.NET Core 3.1 Razor Pages?
Client side work, but after post data I get this server side validation message (ModelState.IsValid = false in my case).客户端工作,但在发布数据后,我收到此服务器端验证消息(在我的情况下为 ModelState.IsValid = false)。 The value '1.000000' is not valid for...
值“1.000000”不适用于...
Model property:模型属性:
[Column(TypeName = "decimal(16, 6)")]
public decimal ValueFactor { get; set; }
View:看法:
<input class="form-control" asp-for="@Model.ValueFactor" />
<span asp-validation-for="ValueFactor" class="text-danger"></span>
I found a solution, the thing is in the regional settings of my computer, where the decimal symbol is a comma.我找到了一个解决方案,问题是在我的计算机的区域设置中,其中十进制符号是逗号。 Server side wants dot for decimal separator, but my client side wants comma as you can see in picture, that's why there is inconsistency, for resolving this just you need to change Decimal symbol type as shown in picture.
服务器端需要小数点分隔符,但我的客户端需要逗号,如图所示,这就是不一致的原因,为了解决这个问题,您只需要更改小数符号类型,如图所示。
Column attribute is Code First Data Annotation Column属性是Code First Data Annotation
For validation of decimal you need a combination of regex and range validations like below:为了验证十进制,您需要结合使用正则表达式和范围验证,如下所示:
[RegularExpression(@"^\d+\.\d{6}$")]
[Range(0, 9999999999.999999)]
RegularExpression attribute above will accept ' any number of digits, follwed by dot(.) and then 6 digits'.上面的正则表达式属性将接受“任意数量的数字,后跟点(.)然后是 6 位数字”。 So following numbers are accepted: 1.000000, 500000.000000 etx.
因此接受以下数字:1.000000、500000.000000 etx。
Range attribute accepts a number of type decimal(16,6) between 0 and 9999999999.999999范围属性接受 0 到 9999999999.999999 之间的类型decimal(16,6) 的数字
Try something like this on server side.在服务器端尝试这样的事情。
public class PersonModel
{
[Required(ErrorMessage = "Required Decimal Number")]
[RegularExpression(@"^[0-9]+(\.[0-9]{1,100})$", ErrorMessage = "Valid Decimal number with maximum decimal places.")]
public string Expenses { get; set; }
}
My model我的模型
[Column(TypeName = "decimal(18,2)")]
public Decimal Bonus { get; set; }
I created a view model.我创建了一个视图模型。
[Display(Name="Ek Ücret")]
[RegularExpression(@"^(\d+),(\d{2})$", ErrorMessage = "Tutar 0,00 - 9999999999,99 aralığında olmalıdır. ")]
public string Bonus { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.