我想指定一个价格的十进制字段必须是>= 0,但我真的不想强加一个最大值。

这是我目前所做的…我不知道正确的做法是什么。

[Range(typeof(decimal), "0", "??"] public decimal Price { get; set; }

当前回答

您可以使用自定义验证:

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public int IntValue { get; set; }

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public decimal DecValue { get; set; }

验证方法类型:

public class ValidationMethods
{
    public static ValidationResult ValidateGreaterOrEqualToZero(decimal value, ValidationContext context)
    {
        bool isValid = true;

        if (value < decimal.Zero)
        {
            isValid = false;
        }

        if (isValid)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(
                string.Format("The field {0} must be greater than or equal to 0.", context.MemberName),
                new List<string>() { context.MemberName });
        }
    }
}

其他回答

我将写入decimal.MaxValue.ToString(),因为这是十进制类型的有效上限,它相当于没有上限。

这样怎么样:

[Range(0.0, Double.MaxValue, ErrorMessage = "The field {0} must be greater than {1}.")]

这应该做你正在寻找的,你可以避免使用字符串。

我打算这样做:

[Range(typeof(decimal), ((double)0).ToString(), ((double)decimal.MaxValue).ToString(), ErrorMessage = "Amount must be greater than or equal to zero.")]

但是,这样做的问题是编译器想要一个常量表达式,这禁止((double)0). tostring()。编译器将接受

[Range(0d, (double)decimal.MaxValue, ErrorMessage = "Amount must be greater than zero.")]

似乎别无选择,只能手动输入最大值。我希望有某种类型的重载,您不需要指定一个。

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }

您可以使用自定义验证:

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public int IntValue { get; set; }

    [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
    public decimal DecValue { get; set; }

验证方法类型:

public class ValidationMethods
{
    public static ValidationResult ValidateGreaterOrEqualToZero(decimal value, ValidationContext context)
    {
        bool isValid = true;

        if (value < decimal.Zero)
        {
            isValid = false;
        }

        if (isValid)
        {
            return ValidationResult.Success;
        }
        else
        {
            return new ValidationResult(
                string.Format("The field {0} must be greater than or equal to 0.", context.MemberName),
                new List<string>() { context.MemberName });
        }
    }
}