gpt4 book ai didi

c# - 自定义验证属性调用另一个验证属性

转载 作者:太空狗 更新时间:2023-10-30 01:22:02 24 4
gpt4 key购买 nike

我想创建一个调用其他验证属性的自定义验证属性。

例如,我想创建一个名为 PasswordValidationAttribute 的属性。我希望它用定义的各种参数(例如正则表达式密码以及最大和最小字符串长度)。

我正在纠结于从哪里开始,确定涉及多少工作并确定它是否可能。将此属性应用于属性后,我希望它能够正确处理 ValidationMessageFor HtmlHelper 并执行服务器端调用。我希望我不需要重新定义它们(否则工作量太大)。

最佳答案

对于 .net 4 它可能看起来像:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class MyValidationAttribute : ValidationAttribute
{
private readonly bool isRequired;

public string Regex { get; set; }

public int StringLength { get; set; }

public MyValidationAttribute(bool isRequired)
{
this.isRequired = isRequired;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var composedAttributes = ConstructAttributes().ToArray();
if (composedAttributes.Length == 0) return ValidationResult.Success;

var errorMsgBuilder = new StringBuilder();
foreach (var attribute in composedAttributes)
{
var valRes = attribute.GetValidationResult(value, validationContext);
if (valRes != null && !string.IsNullOrWhiteSpace(valRes.ErrorMessage))
errorMsgBuilder.AppendLine(valRes.ErrorMessage);
}
var msg = errorMsgBuilder.ToString();
if (string.IsNullOrWhiteSpace(msg))
return ValidationResult.Success;
return new ValidationResult(msg);
}

private IEnumerable<ValidationAttribute> ConstructAttributes()
{
if (isRequired)
yield return new RequiredAttribute();
if (Regex != null)
yield return new RegularExpressionAttribute(Regex);
if (StringLength > 0)
yield return new StringLengthAttribute(StringLength);
}
}

用法:

[MyValidationAttribute(true, Regex = "[a-z]*", StringLength = 3)]
public string Name { get; set; }

.net 3.5 中有一个限制,您不能从底层属性动态构造消息值(至少我没能通过它)。每个整个属性只能设置一条消息。

所有更改都在方法 IsValid 中。

public override bool IsValid(object value)
{
var composedAttributes = ConstructAttributes().ToArray();
if (composedAttributes.Length == 0) return true;
return composedAttributes.All(a => a.IsValid(value));
}

ErrorMessage 注释:

.net 3.5中ValidationAttributeIsValid方法的返回值不是ValidationResult而是bool。当我尝试设置 ErrorMessage 时,我收到了错误消息,指出 value can be set only once

关于c# - 自定义验证属性调用另一个验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14666059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com