0

I'm looking of a way to perform data compare validation that validates "from" > "To" on the data model client and server. Like this:

public sealed class CompareDatesValidatorAttribute : ValidationAttribute { private string _dateToCompareField;

    public string FieldToCompare
    {
        get { return _dateToCompareField; }
        set { _dateToCompareField=value; }
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(this.ErrorMessageString, name, FieldToCompare);

    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var dateToCompare = validationContext.ObjectType.GetProperty(_dateToCompareField);
        var dateToCompareValue = dateToCompare.GetValue(validationContext.ObjectInstance, null);
        if (dateToCompareValue != null && value != null && (DateTime)value < (DateTime)dateToCompareValue)
        {
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }

I already developed a server validation , but I'm looking build in solution for this. that works in client and server.

Any help would be appreciated,

10x Rony

ron
  • 625
  • 2
  • 6
  • 17
  • have you checked out http://foolproof.codeplex.com/ to see how they do it? – Slicksim May 22 '13 at 07:54
  • @Slicksim, I tried install this but I keep getting error that Sys is undefined. I have the feeling that its too old and it doesn't work with modernizr. I saw it requires microsoftAjax and it's old. – ron May 22 '13 at 09:00
  • on what MVC version are you working ? – ron May 22 '13 at 09:01
  • it has implementations for unobtrusive as well, i use it in my mvc projects when i am doing a lot of form work. it might get out of sync if you are loading the script files in via modernizr later on, so it might be worth loading it at the end of the doc when all the other scripts have loaded. one note, i tend to use date.js to override it's date validation, i found it to be a little lacking when comparing valid dates – Slicksim May 22 '13 at 09:20
  • I also tried FluentValidator http://fluentvalidation.codeplex.com/ but this is server side only. – ron May 22 '13 at 10:36
  • You could create a client validation rule for the jquery validation as described in http://stackoverflow.com/questions/833997/end-date-greater-than-start-date-jquery-validation. Then you need to link your server side validation with the client side one, by implementing the method `GetClientValidationRules` in your ValidationAttribute, and creating a new adaptor in javascript as in the following answer http://stackoverflow.com/questions/13751113/mvc3-modelclientvalidationrule-compare-2-different-fields-adding-a-required-fla/13777713#13777713 – Daniel J.G. May 22 '13 at 12:18

0 Answers0