This is a migrated thread and some comments may be shown as answers.

[Solved] Date not validating with custom model attribute

1 Answer 88 Views
Date/Time Pickers
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Howard
Top achievements
Rank 1
Howard asked on 08 Mar 2012, 04:55 AM
Dear Telerik Team,

I've got a model validation IsDateAfter like
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public sealed class IsDateAfter : ValidationAttribute, IClientValidatable
    {
        private readonly string dateToCompare;
        private readonly bool allowEqualDates;
 
        public IsDateAfter(string dateToCompare, bool allowEqualDates = false)
        {
            this.dateToCompare = dateToCompare;
            this.allowEqualDates = allowEqualDates;
        }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.dateToCompare);
            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", this.dateToCompare));
            }
             
            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
 
            if (propertyTestedValue != null)
            {
                if (!(propertyTestedValue is DateTime))
                {
                    propertyTestedValue = DateTime.ParseExact(propertyTestedValue.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
                }
            }
 
            if (value == null || !(value is DateTime))
            {
                return ValidationResult.Success;
            }
 
            if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
            {
                return ValidationResult.Success;
            }
 
            //compare values
            if ((DateTime)value >= (DateTime)propertyTestedValue)
            {
                if (this.allowEqualDates)
                {
                    return ValidationResult.Success;
                }
                if ((DateTime)value > (DateTime)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }
 
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessageString,
                ValidationType = "isdateafter"
            };
            rule.ValidationParameters["datetocompare"] = this.dateToCompare;
            rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
 
            yield return rule;
        }
    }

For client side, i've got a file customvalidation.js
//date validator start
    $.validator.unobtrusive.adapters.add(
        'isdateafter', ['datetocompare', 'allowequaldates'], function (options) {
            options.rules['isdateafter'] = options.params;
            options.messages['isdateafter'] = options.message;
        });
 
        $.validator.addMethod("isdateafter", function (value, element, params) {           
            var parts = element.name.split(".");
            var prefix = "";
            if (parts.length > 1)
                prefix = parts[0] + ".";
            var startdatevalue = $('input[name="' + prefix + params.datetocompare + '"]').val();
            if (!value || !startdatevalue)
                return true;
 
            var startSplit = startdatevalue.split('/');
            var newStartDateValue = new Date(startSplit[2], startSplit[1], startSplit[0]);
            var startTimeStamp = newStartDateValue.getTime();
 
            var valueSplit = value.split('/');
            var newValue = new Date(valueSplit[2], valueSplit[1], valueSplit[0]);
            var valueTimeStamp = newValue.getTime();
 
            return (params.allowequaldates) ? startTimeStamp <= valueTimeStamp :
            startTimeStamp < valueTimeStamp;
        });
    //date validator end

My model is
public class FleetDecommissionModel
    {
        [ScaffoldColumn(false)]
        public int FLEET_ID { get; set; }
 
        [Display(Name = "Delivery date:")]
        public string DELIVERY_DATE { get; set; }
 
        [Display(Name = "Decommissioning date:")]
        [Required]
        [IsDateAfter("DELIVERY_DATE", false, ErrorMessage="Date must not be before delivery date")]
        public DateTime? DECOMMISSIONING_DATE { get; set; }
 
    }

I'm using telerik datepickerfor extersion for decommissioning date like
@(Html.Telerik().DatePickerFor(f=>f.DECOMMISSIONING_DATE)                           
            .HtmlAttributes(new { id = "DatePicker_wrapper" })                           
            .Format("dd/MM/yyyy")
     )

I've got all the files for unobtrusive calls like jquery.unobtrusive-ajax.min.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js and customvalidation.js in my page, but it is not firing the client side validation.

Please let me know what I'm doing wrong here.
Thank you

1 Answer, 1 is accepted

Sort by
0
Georgi Krustev
Telerik team
answered on 12 Mar 2012, 09:08 AM
Hello Niroj,

I am not sure where could be the problem depending on the given information. Could you please check whether the client validation works without the DatePicker on the page? If the validation works we will need a repro project to  investigate the issue locally.

Kind regards,
Georgi Krustev
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now.
Tags
Date/Time Pickers
Asked by
Howard
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Share this question
or