以下条件的正确货币数据注释是什么?
- 小数点后两位的数字金额
- 最低金额1.00美元;最高金额25000.00美元
这是我的田地。
public string amount {get; set;}
要检查小数位数,您可以使用RegularExpression注释和正确的正则表达式来匹配您的数字格式:
[RegularExpression(@"(.d{2}){1}$")]
要检查最小值和最大值,我们必须创建自己的自定义属性
[MinDecimalValue(1.00)]
[MaxDecimalValue(25000.00)]
public string amount { get; set; }
我们可以通过创建一个从ValidationAttribute派生的类并重写IsValid方法来实现这一点。
请参阅下面我的实现。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MaxDecimalValueAttribute : ValidationAttribute
{
private double maximum;
public MaxDecimalValueAttribute(double maxVal)
: base("The given value is more than the maximum allowed.")
{
maximum = maxVal;
}
public override bool IsValid(object value)
{
var stringValue = value as string;
double numericValue;
if(stringValue == null)
return false;
else if(!Double.TryParse(stringValue, out numericValue) || numericValue > maximum)
{
return false;
}
return true;
}
}
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class MinDecimalValueAttribute : ValidationAttribute
{
private double minimum;
public MinDecimalValueAttribute(double minVal)
: base("The given value is less than the minimum allowed.")
{
minimum = minVal;
}
public override bool IsValid(object value)
{
var stringValue = value as string;
double numericValue;
if (stringValue == null)
return false;
else if (!Double.TryParse(stringValue, out numericValue) || numericValue < minimum)
{
return false;
}
return true;
}
}
您可以阅读更多关于如何创建自己的属性的内容,而且此代码还需要更多改进。
希望这能有所帮助!
请使用链接后面的Culture info类。