Client side validation for custom annotation Asp.Net MVC 4

后端 未结 2 499
清酒与你
清酒与你 2021-02-02 03:57

I am referring this article:

http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

which shows how to create custom annotation in Asp.Net MVC 2

2条回答
  •  一向
    一向 (楼主)
    2021-02-02 04:54

    The key thing missing here is that the server-side validator must implement the IClientValidatable interface:

    public class RateRequiredIfCustomIndexRateAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            return false;
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "raterequiredifcustomindexrate"
            };
        }
    }
    

    Once you do that, the client-side validation should be hooked up properly. You can verify this by making sure that your input field has an attribute "data-val-raterequiredifcustomindexrate" attribute.

提交回复
热议问题