Search code examples
asp.netasp.net-mvc-2model-validation

ASP.NET MVC 2.0 Custom Client Validation


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.


Solution

  • 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.