使用属性验证数字中的位数

Validate amount of digits in number with an attribute

我目前正在开发 .net5.0 应用程序。

在我的视图模型中 class 我需要验证数字输入的长度。

要验证的 属性 称为“PostalCode”,在数据库中具有等效项:NUMBER(4,0)

邮政编码可以是数字,不带小数值,范围为 0000 到 9999。 重要的是,该值必须是 4 位数字。

到目前为止我试过这段代码:

[Range(0, 9999, ErrorMessageResourceType = "The PostalCode must be 4 digits long.")]
public int PostalCode { get; set; }

你知道如何正确验证最小长度为 4 位的 PostalCode 吗?

你知道如何解决这个问题吗?

试试这个:


 [RegularExpression(@"^(\d{4})$", ErrorMessage = "The PostalCode must be 4 digits long.")]
public int PostalCode { get; set; }