c# - 2个属性浮动范围Asp .Net Core之间的自定义验证
问题描述
我在模型中有这两个属性
public class Geometria
{
public int Id { get; set; }
public string Componente { get; set; }
[Range(0, float.MaxValue)]
public float ToleranciaInferior { get; set; }
[Range(0,float.MaxValue)]
public float ToleranciaSuperior { get; set; }
}
属性 ToleranciaSuperior 不能与 ToleranciaInferior 相同或相等。
我怎样才能通过注释来实现这一点?
解决方案
将自定义验证逻辑放入视图模型本身会更方便,除非您发现自己在多个视图模型上执行此操作。
public class Geometria : IValidatableObject
{
public int Id { get; set; }
public string Componente { get; set; }
[Range(0, float.MaxValue)]
public float ToleranciaInferior { get; set; }
[Range(0,float.MaxValue)]
public float ToleranciaSuperior { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (ToleranciaInferior == ToleranciaSuperior)
{
yield return new ValidationResult(
"Your error message",
new string[] {
nameof(ToleranciaInferior), nameof(ToleranciaSuperior)
});
}
}
}
推荐阅读
- c# - 当我在 C# 中使用 inkcanvas1.Strokes.Erase 语句时,WPF-InkCanvas StrokeErased 事件未触发
- python - 遍历数据帧,编写字典并将浮点值附加到键
- javascript - React 中的动态 GraphQL 突变与模板文字
- javascript - 如何使用 Javascript 访问严格/显式 href 值?
- chart.js - 如何在 x 轴上显示半小时刻度
- wkhtmltopdf - 文本在表中重叠
- datomic - 排除某些 id 的查询
- kotlin - 模拟每个 {}.throws() 异常失败测试
- asp.net-core - Blazor - 使用移动设备访问已发布网站时出错
- google-analytics - 主机名流量和 ISP 域访问有什么区别?