开发者

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 i开发者_C百科nvoked 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.


<% =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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜