我可以使用 DataAnnotations 来验证集合 属性 吗?
Can I use DataAnnotations to validate a collection property?
我有一个 WebAPI2 控制器模型,它有一个接受字符串集合(列表)的字段。有没有一种方法可以为字符串指定 DataAnnotations(例如 [MaxLength]),以通过验证确保列表中字符串的 none 长度 > 50?
public class MyModel
{
//...
[Required]
public List<string> Identifiers { get; set; }
// ....
}
我不想创建一个新的 class 只是为了包装字符串。
您可以编写自己的验证属性,例如如下:
public class NoStringInListBiggerThanAttribute : ValidationAttribute
{
private readonly int length;
public NoStringInListBiggerThanAttribute(int length)
{
this.length = length;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var strings = value as IEnumerable<string>;
if(strings == null)
return ValidationResult.Success;
var invalid = strings.Where(s => s.Length > length).ToArray();
if(invalid.Length > 0)
return new ValidationResult("The following strings exceed the value: " + string.Join(", ", invalid));
return ValidationResult.Success;
}
}
您可以将它直接放在您的 属性 上:
[Required, NoStringInListBiggerThan(50)]
public List<string> Identifiers {get; set;}
我知道这个问题由来已久,但对于那些偶然发现它的人来说,这里是我的自定义属性版本,灵感来自已接受的答案。它利用 StringLengthAttribute 来完成繁重的工作。
/// <summary>
/// Validation attribute to assert that the members of an IEnumerable<string> property, field, or parameter does not exceed a maximum length
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerableStringLengthAttribute : StringLengthAttribute
{
/// <summary>
/// Constructor that accepts the maximum length of the string.
/// </summary>
/// <param name="maximumLength">The maximum length, inclusive. It may not be negative.</param>
public EnumerableStringLengthAttribute(int maximumLength) : base(maximumLength)
{
}
/// <summary>
/// Override of <see cref="StringLengthAttribute.IsValid(object)" />
/// </summary>
/// <remarks>
/// This method returns <c>true</c> if the <paramref name="value" /> is null.
/// It is assumed the <see cref="RequiredAttribute" /> is used if the value may not be null.
/// </remarks>
/// <param name="value">The value to test.</param>
/// <returns><c>true</c> if the value is null or the length of each member of the value is between the set minimum and maximum length</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
public override bool IsValid(object? value)
{
return value is null || ((IEnumerable<string>)value).All(s => base.IsValid(s));
}
}
编辑:base.IsValid(s)
returns 如果 s
为空,则为真,因此如果字符串成员不能为空,请改用:
public override bool IsValid(object? value)
{
return value is null || ((IEnumerable<string>)value).All(s => !string.IsNullOrEmpty(s) && base.IsValid(s));
}
我有一个 WebAPI2 控制器模型,它有一个接受字符串集合(列表)的字段。有没有一种方法可以为字符串指定 DataAnnotations(例如 [MaxLength]),以通过验证确保列表中字符串的 none 长度 > 50?
public class MyModel
{
//...
[Required]
public List<string> Identifiers { get; set; }
// ....
}
我不想创建一个新的 class 只是为了包装字符串。
您可以编写自己的验证属性,例如如下:
public class NoStringInListBiggerThanAttribute : ValidationAttribute
{
private readonly int length;
public NoStringInListBiggerThanAttribute(int length)
{
this.length = length;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var strings = value as IEnumerable<string>;
if(strings == null)
return ValidationResult.Success;
var invalid = strings.Where(s => s.Length > length).ToArray();
if(invalid.Length > 0)
return new ValidationResult("The following strings exceed the value: " + string.Join(", ", invalid));
return ValidationResult.Success;
}
}
您可以将它直接放在您的 属性 上:
[Required, NoStringInListBiggerThan(50)]
public List<string> Identifiers {get; set;}
我知道这个问题由来已久,但对于那些偶然发现它的人来说,这里是我的自定义属性版本,灵感来自已接受的答案。它利用 StringLengthAttribute 来完成繁重的工作。
/// <summary>
/// Validation attribute to assert that the members of an IEnumerable<string> property, field, or parameter does not exceed a maximum length
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class EnumerableStringLengthAttribute : StringLengthAttribute
{
/// <summary>
/// Constructor that accepts the maximum length of the string.
/// </summary>
/// <param name="maximumLength">The maximum length, inclusive. It may not be negative.</param>
public EnumerableStringLengthAttribute(int maximumLength) : base(maximumLength)
{
}
/// <summary>
/// Override of <see cref="StringLengthAttribute.IsValid(object)" />
/// </summary>
/// <remarks>
/// This method returns <c>true</c> if the <paramref name="value" /> is null.
/// It is assumed the <see cref="RequiredAttribute" /> is used if the value may not be null.
/// </remarks>
/// <param name="value">The value to test.</param>
/// <returns><c>true</c> if the value is null or the length of each member of the value is between the set minimum and maximum length</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
public override bool IsValid(object? value)
{
return value is null || ((IEnumerable<string>)value).All(s => base.IsValid(s));
}
}
编辑:base.IsValid(s)
returns 如果 s
为空,则为真,因此如果字符串成员不能为空,请改用:
public override bool IsValid(object? value)
{
return value is null || ((IEnumerable<string>)value).All(s => !string.IsNullOrEmpty(s) && base.IsValid(s));
}