0

I am trying to write a client side validator for angularjs using fluent validation. I used the methods outlined by Darin Dimitrov here. Everything works fine except I can't figure out how to access the greater than value I set up in my validation rule. I need this so I can have my angular directive validate this value for me.

Any ideas? Thanks.

Here is my Rule:

RuleFor(m => m.dropDownListId).GreaterThan(0).WithMessage("Required");

Here is my override code:

public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules()) yield break;

            var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
            var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());

           var rule = new ModelClientValidationRule
            {
                ValidationType = VALIDATIONTYPE,
                ErrorMessage = message
            };

            //CompareAttribute is deprecated and I can't figure out the new syntax
            //also 'MemberToCompare' is always null
            rule.ValidationParameters["greaterthan"] = CompareAttribute.FormatPropertyForClientValidation(validator.MemberToCompare.Name);

            //what I am trying to do is
            rule.ValidationParameters.Add("greaterthan", "the value I setup in my rule");

            yield return rule;
        }
Community
  • 1
  • 1
trevorc
  • 3,023
  • 4
  • 31
  • 49

1 Answers1

0

I hate to answer my own questions, especially when I have missed the obvious but this may help someone.

Because 'GreaterThan' validates a number you need to use Validator.ValueToCompare. Duh.

Here is the correct way.

 public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            if (!ShouldGenerateClientSideRules()) yield break;

            var validator = Validator as GreaterThanValidator;
            if(validator == null)
                throw new ArgumentException("greaterThanValidator");

            var valueToCompare = validator.ValueToCompare;
            var formatter = new MessageFormatter().AppendPropertyName(Rule.PropertyName);
            var message = formatter.BuildMessage(Validator.ErrorMessageSource.GetString());

           var rule = new ModelClientValidationRule
            {
                ValidationType = VALIDATIONTYPE,
                ErrorMessage = message
            };

            rule.ValidationParameters.Add("min", valueToCompare);

            yield return rule;
        }
trevorc
  • 3,023
  • 4
  • 31
  • 49