我为一个整数创建了一个自定义验证器,以检查大于0的输入。效果很好。
整数的自定义验证
using System;
using System.ComponentModel.DataAnnotations;
public class GeaterThanInteger : ValidationAttribute
{
private readonly int _val;
public GeaterThanInteger(int val)
{
_val = val;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return Convert.ToInt32(value) > _val;
}
}呼叫码
[GeaterThanInteger(0)]
public int AccountNumber { get; set; }用于十进制的自定义校验器
我试图为十进制创建类似的验证器,以检查大于0的输入。不过,这一次我遇到了编译器错误。
public class GreaterThanDecimal : ValidationAttribute
{
private readonly decimal _val;
public GreaterThanDecimal(decimal val)
{
_val = val;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return Convert.ToDecimal(value) > _val;
}
}呼叫码
[GreaterThanDecimal(0)]
public decimal Amount { get; set; }编译器错误(指向GreaterThanDecimal(0))
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type我尝试了几种组合,
[GreaterThanDecimal(0M)]
[GreaterThanDecimal((decimal)0)]但不起作用。
我查看了ValidationAttribute的定义和文档,但我仍然迷失了方向。
抱怨什么错误?
在这种情况下,是否有其他方法来验证大于0的Decimal?
发布于 2018-08-16 17:49:50
@JonathonChase在评论中回答了这个问题,我想我应该在这里用修改过的代码示例来完成答案,以防有人遇到同样的问题。
抱怨什么错误?
因为调用[GreaterThanDecimal(0)]试图将十进制作为属性参数传递,所以CLR不支持这一点。请参阅use decimal values as attribute params in c#?
溶液
将参数类型更改为double或int
public class GreaterThanDecimalAttribute : ValidationAttribute
{
private readonly decimal _val;
public GreaterThanDecimalAttribute(double val) // <== Changed parameter type from decimal to double
{
_val = (decimal)val;
}
public override bool IsValid(object value)
{
if (value == null) return false;
return Convert.ToDecimal(value) > _val;
}
}发布于 2022-06-08 04:26:52
尝试使用以下代码:
[Range(1, int.MaxValue, ErrorMessage = "Value Must Bigger Than {1}")]发布于 2021-01-24 02:52:41
使用范围属性。对小数也很有用。
[Range(0.01, 99999999)]https://stackoverflow.com/questions/51881895
复制相似问题