Search code examples
asp.net-mvc-3custom-attributesclient-side-validation

client side validation in MVC3 not working


below is the code somehow client side validation is not working...I searched couple of questions in this forum and wrote this..

here is the custom validation attribute "startDateAttribute"

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class StartDateAttribute : ValidationAttribute, IClientValidatable
    {
        public StartDateAttribute ()
        {
        }

        public override bool IsValid(object value)
        {   
            var date = (DateTime)value;
            if (date.Date >= DateTime.Now.Date)
            {
                return true;
            }
            return false;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "DateRange"
            };
        }
    }

    [CurrentDateAttribute(ErrorMessage = "select the correct date")]    
    public DateTime? StartDate { get; set; }

here is the JQuery code added

      jQuery.validator.addMethod('DateRange', function (value, element, params) {
     var d = new Date();         
     var currentDate = (d.getMonth()+1)  + "/"+d.getDate()+ "/" + d.getFullYear() ;
    return value >= currentDate;
});

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('DateRange', { }, function (options) {
    options.rules['DateRange'] = true;
    options.messages['DateRange'] = options.message;
});

Solution

  • One of the requirements of client side validation is that the ValidationType and the adapter name should match and should be lower case.

    Change the ValidationType and adapter name to 'daterange' and check