0

I am trying to make a validator that will make sure that at least 2 items are selected. The validator works correctly on the server side but the client side code never gets executed.

Here is the code:

 Sys.Mvc.ValidatorRegistry.validators["country"] = function (rule) {

        var min = rule.ValidationParameters["min"];        

        return function (value, context) {

            if (value >= min) return true;

            return rule.ErrorMessage;

        };
    };  

And here is the validator code:

  public class CountryValidator : DataAnnotationsModelValidator<CustomValidations.CountryAttribute>
    {
        private int _minimum;
        private string _message; 

        public CountryValidator(ModelMetadata metadata, ControllerContext context, CustomValidations.CountryAttribute attribute) : base(metadata,context,attribute)
        {
            _minimum = attribute.Minimum;
            _message = attribute.ErrorMessage; 
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRule()
            {
                ErrorMessage = _message,
                ValidationType = "country"
            };

            rule.ValidationParameters.Add("min", _minimum);
            return new[] { rule };
        }


    }

I have even registered the validation adapter in global.asax file:

  protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(AgeAttribute), typeof(AgeValidator));
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CountryAttribute),typeof(CountryValidator));
        }

I am thinking that the validator only works with the elements that have a value property like textboxes etc.

UPDATE 1:

EnableClientValidation is invoked correctly and all the required JS files are included in the project. It seems like I need to attach the onblur to the context. I will try that and post the results.

hutchonoid
  • 32,982
  • 15
  • 99
  • 104
azamsharp
  • 19,710
  • 36
  • 144
  • 222

3 Answers3

0

<% =Html.EnableClientValidation(); %> needs to be in your view somewhere. Also make sure you reference MicrosoftAjax.js and MicrosoftMvcValidation.js in the same view (before your js function).

Byron Sommardahl
  • 12,743
  • 15
  • 74
  • 131
0

Either your missing MicrosoftMvcAjax.js or you need to implement your custom validation in jQuery as described on Mr. Haack's website http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

I think it is because the default validation is invoked on the onblur event of the input textbox. And for a listbox this event was not being thrown.

azamsharp
  • 19,710
  • 36
  • 144
  • 222