首页 > 解决方案 > 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 相同或相等。

我怎样才能通过注释来实现这一点?

标签: c#validationasp.net-core-2.2

解决方案


将自定义验证逻辑放入视图模型本身会更方便,除非您发现自己在多个视图模型上执行此操作。

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) 
                });
        }
    }
}


推荐阅读