-2

how can i to put conditional Required Attribute into class? i tried the following code and it doesn't work.

public partial class Zone
{
    [RequireCondition ]
    public int LastCount { get; set; }
}
public class RequireCondition : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var Zone = (Zone)validationContext.ObjectInstance;
            if (Zone.LastCount < 1)
            {
                return new ValidationResult("Last Count value must be greater than one.");
            }
            else
           {
                return ValidationResult.Success;
           }
        }
    }
user3835327
  • 1,194
  • 1
  • 14
  • 44
  • What does "it doesn't work" mean? What did you find when you debugged it? – ProgrammingLlama Nov 20 '17 at 02:58
  • the condition cant be work, i still can proceed whenever the value is less than 1 – user3835327 Nov 20 '17 at 03:01
  • [Downvote reason](http://idownvotedbecau.se/itsnotworking/) - please read, it's educational. You can find out the value of `value` by placing a breakpoint on the line starting `var Zone =` and inspecting the value of `value`. – ProgrammingLlama Nov 20 '17 at 03:02

1 Answers1

1

Try this?

public partial class Zone
{
    [RequireCondition(1)]
    public int LastCount { get; set; }
}

public class RequireConditionAttribute : ValidationAttribute
 {
     private int _comparisonValue;

     public RequireCondition(int comparisonValue)
     {
        _comparisonValue = comparisonValue;
     }

     protected override ValidationResult IsValid(object value, ValidationContext validationContext)
      {              
        if (value is int && (int)value < comparisonValue)
            {
              return new ValidationResult($"{validationContext.DisplayName} value must be greater than one.");
            }

            return ValidationResult.Success;
        }
    }
zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • hi, there's an error, operator '<' cannot be applied to operands of type 'object' and 'int' .. in line of (value > comparisonvalue) – user3835327 Nov 20 '17 at 03:07