我正在尝试创建一个自定义验证,上面写着“如果 otherValue 为真,则该值必须大于 0。我能够获取该值,但我目前设置 otherValue 的方式,我只有属性的名称,而不是值。可能是因为它作为字符串传入。这个属性将在 5 或 6 个不同的属性上,每次都会调用不同的 otherValue。寻求有关如何获取的帮助otherValue 的实际值(它是一个布尔值)。
这是我当前的代码:
public class MustBeGreaterIfTrueAttribute : ValidationAttribute, IClientValidatable
{
// get the radio button value
public string OtherValue { get; set; }
public override bool IsValid(object value)
{
// Here is the actual custom rule
if (value.ToString() == "0")
{
if (OtherValue.ToString() == "true")
{
return false;
}
}
// If all is ok, return successful.
return true;
}
======================编辑=========================
这就是我现在的位置,它有效!现在我需要参考如何制作它,以便在模型中添加属性时可以输入不同的 errorMessage:
public class MustBeGreaterIfTrueAttribute : ValidationAttribute, IClientValidatable
{
// get the radio button value
public string OtherProperty { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var otherPropertyInfo = context.ObjectInstance.GetType();
var otherValue = otherPropertyInfo.GetProperty(OtherProperty).GetValue(context.ObjectInstance, null);
// Here is the actual custom rule
if (value.ToString() == "0")
{
if (otherValue.ToString().Equals("True", StringComparison.InvariantCultureIgnoreCase))
{
return new ValidationResult("Ensure all 'Yes' answers have additional data entered.");
}
}
// If all is ok, return successful.
return ValidationResult.Success;
}
// Add the client side unobtrusive 'data-val' attributes
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ValidationType = "requiredifyes";
rule.ErrorMessage = this.ErrorMessage;
rule.ValidationParameters.Add("othervalue", this.OtherProperty);
yield return rule;
}
}
所以我应该能够做到这一点:
[MustBeGreaterIfTrue(OtherProperty="EverHadRestrainingOrder", ErrorMessage="Enter more info on your RO.")]
public int? ROCounter { get; set; }