如何在C#中创建自定义验证属性,用于验证`IEnumerable`是否包含不同的值?

huangapple go评论73阅读模式
英文:

How can I make a custom validation attribute in C# which validates if an `IEnumerable` contains distinct values?

问题

以下是您要翻译的代码部分:

public class Payload
{
    [DistinctValues]
    public IEnumerable<string> Names { get; set; }
}
public class DistinctValuesAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //validation logic here
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //validation logic here
    }
}
英文:

I want to be able to use the attribute in a ASP.NET Core Web API to validate properties in payload objects. Here's an example of how I would want it to work.

public class Payload
{
    [DistinctValues]
    public IEnumerable&lt;string&gt; Names { get; set; }
}

From what I've seen, the custom attribute should inherit ValidationAttribute and override the IsValid method. Here's what I've got so far. I don't know how to create the validation logic.

public class DistinctValuesAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //validation logic here
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        //validation logic here
    }
}

答案1

得分: 0

In this bool IsValid(object value) method, to find whether the list contains any duplicate value, you can compare the count of distinct values against the total count of values.

values.Distinct().Count() == values.Count();

In this ValidationResult IsValid(object value, ValidationContext validationContext) method,

When the count of values is not equal (fail validation), you should return an instance of ValidationResult.

For success validation, you should return ValidationResult.Success.

using System.Linq;

public class DistinctValuesAttribute : ValidationAttribute
{	
	public DistinctValuesAttribute()
	{
		ErrorMessage = $&quot;{this.TypeId} contains duplicate value&quot;;
	}
	
	public DistinctValuesAttribute(string errorMessage)
	{
		ErrorMessage = errorMessage;
	}

    public override bool IsValid(object value)
    {
		IEnumerable&lt;string&gt; values = value as IEnumerable&lt;string&gt;;
		
		if (values != null &amp;&amp; values.Any())
		{
			return values.Distinct().Count() == values.Count();
		}	
		
		return true;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
		if (!IsValid(value))
		{
			return new ValidationResult(this.ErrorMessage, new List&lt;string&gt; { this.TypeId.ToString() });
		}
		
		return ValidationResult.Success;
    }
}
英文:

In this bool IsValid(object value) method, to find whether the list contains any duplicate value, you can compare the count of distinct values against the total count of values.

values.Distinct().Count() == values.Count();

In this ValidationResult IsValid(object value, ValidationContext validationContext) method,

When the count of values is not equal (fail validation), you should return an instance of ValidationResult.

For success validation, you should return ValidationResult.Success.

using System.Linq;

public class DistinctValuesAttribute : ValidationAttribute
{	
	public DistinctValuesAttribute()
	{
		ErrorMessage = $&quot;{this.TypeId} contains duplicate value&quot;;
	}
	
	public DistinctValuesAttribute(string errorMessage)
	{
		ErrorMessage = errorMessage;
	}

    public override bool IsValid(object value)
    {
		IEnumerable&lt;string&gt; values = value as IEnumerable&lt;string&gt;;
		
		if (values != null &amp;&amp; values.Any())
		{
			return values.Distinct().Count() == values.Count();
		}	
		
		return true;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
		if (!IsValid(value))
		{
			return new ValidationResult(this.ErrorMessage, new List&lt;string&gt; { this.TypeId.ToString() });
		}
		
		return ValidationResult.Success;
    }
}

答案2

得分: 0

使用上一个答案的帮助,我成功找到了我所需的解决方案。

public class DistinctValuesAttribute : ValidationAttribute
{
    public DistinctValuesAttribute()
    {
        ErrorMessage = "集合应包含不同的值";
    }

    public DistinctValuesAttribute(string errorMessage)
    {
        ErrorMessage = errorMessage;
    }

    public override bool IsValid(object value)
    {
        var values = value as IEnumerable<object>;

        if (values != null && values.Any())
        {
            return values.Distinct().Count() == values.Count();
        }

        return true;
    }
}
英文:

With the help of the previous answer, I managed to find a solution for what I needed.

public class DistinctValuesAttribute : ValidationAttribute
    {
        public DistinctValuesAttribute()
        {
            ErrorMessage = $&quot;The collection should contain distinct values&quot;;
        }

        public DistinctValuesAttribute(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public override bool IsValid(object value)
        {
            var values = value as IEnumerable&lt;object&gt;;

            if (values != null &amp;&amp; values.Any())
            {
                return values.Distinct().Count() == values.Count();
            }

            return true;
        }
    }

huangapple
  • 本文由 发表于 2023年3月9日 16:19:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定