1

我正在尝试创建一个自定义验证,上面写着“如果 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; }
4

3 回答 3

8

ValidationAttribute两种IsValid方法,对于您的场景,您必须使用其他人。

  public class MustBeGreaterIfTrueAttribute : ValidationAttribute
  {
    // name of the OtherProperty. You have to specify this when you apply this attribute
    public string OtherPropertyName { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      var otherProperty = validationContext.ObjectType.GetProperty(OtherPropertyName);

      if (otherProperty == null)
        return new ValidationResult(String.Format("Unknown property: {0}.", OtherPropertyName));

      var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);

      if (value.ToString() == "0")
      {
        if (otherPropertyValue != null && otherPropertyValue.ToString() == "true")
        {
          return null;
        }
      }

      return new ValidationResult("write something here");
    }
  }

示例用法:

public class SomeModel
{
    [MustBeGreaterIf(OtherPropertyName="Prop2")]
    public string Prop1 {get;set;}
    public string Prop2 {get;set;}
}

参考: http: //www.concurrentdevelopment.co.uk/blog/index.php/2011/01/custom-validationattribute-for-comparing-properties/

于 2012-10-25T17:21:03.540 回答
0

我有点难以理解你想要做什么,但是,

如果你想得到 OtherValue 的布尔表示,你可以这样做

bool.Parse(this.OtherValue);


此外,对于字符串比较,有时有助于将大小写和空格从图片中剔除

if (this.OtherValue.ToString().ToLower().Trim() == "true")
于 2012-10-25T14:54:11.977 回答
0

validationContext 具有 ObjectInstance ,它是 SomeModel 类的一个实例,因此您可以使用: (validationContext.ObjectInstance as SomeModel).Prop1/Prop2

于 2017-04-20T15:33:28.787 回答