2 个属性浮动范围 Asp .Net Core 之间的自定义验证

Custom Validation between 2 properties float range 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) 
                });
        }
    }
}