c# - 如何为多个属性重用多个数据注释
问题描述
我想使用以下数据注释:
[RegularExpression(@"^\d+\.\d{0,2}$", ErrorMessage = "Invalid price entered, please re-check the price and try again.")]
[Range(0, 999999.99, ErrorMessage = "The price must be less than £999999.99")]
对于我的类中的所有价格属性,但我不想重用注释并希望将它们组合成例如 [PriceValidation] 并将其打印在所有属性之上。这可以做到吗?TIA
解决方案
您可以创建自己的自定义验证属性,该属性将封装所需的逻辑。对于初学者来说是这样的:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class PriceValidationAttribute : ValidationAttribute
{
private static readonly Regex Regex = new Regex(@"^\d+\.\d{0,2}$", RegexOptions.Compiled);
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
if (stringValue != null && !Regex.IsMatch(stringValue))
{
return new ValidationResult("Invalid price entered, please re-check the price and try again.");
}
var doubleValue = Convert.ToDouble(value);
if (doubleValue > 999999.99 || doubleValue < 0)
{
return new ValidationResult("The price must be less than £999999.99");
}
return ValidationResult.Success;
}
}
您也可以考虑使用流利的验证库。
推荐阅读
- python - Pandas 将函数应用于列并从函数返回中填充 2 列
- postgresql - 允许用户访问 PostgreSQL 中的特定表
- android - 我想在 Kotlin 中使用 AndroidStudio 获取当前月份的最后三个月,使用 viwepager2 的选项卡布局
- angular - 从 typeOf ngrx 效果中获取参数
- angular - 如何强制 Mat Tab 主体为非活动选项卡呈现/绑定 html 元素
- foreach - 嵌套在 jstl 中的 forEach
- ios - 如何在 .interactive keyboardDismissMode 集合视图的“下拉”键盘中间调整底部约束?
- python - python pandas:减去两个日期时间得到零
- r - Posixct 日期的条件
- javascript - Laravel如何在Javascript var中使用刀片代码?