Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8276151
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T08:17:39+00:00 2026-06-08T08:17:39+00:00

This is the simplified model : public class Person { public int Id; public

  • 0

This is the simplified model :

public class Person {
   public int Id;
   public string Name;
}

public class Task {
  public int Id;
  public int PersonId;
  public DateTime StartDate;
  [GreaterThan("StartDate")]
  public DateTime EndDate;
}

To validate the EndDate >= StartDate, i write general GreaterThanAttribute. The server side is trivial, but i have problem on client side validation.

My GreaterThanAttribute got the other property (ex: “StartDate”) from constructor, then i pass this other property name to javascript as validation rule. But it won’t work, because the JS will not found this element, because MVC will render & named it as “Task.StartDate”, not “StartDate”.

My question is, how i can get the prefix which will be used by the controller to render my model inside IClientValidatable.GetClientValidationRules() ?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T08:17:40+00:00Added an answer on June 8, 2026 at 8:17 am

    Here’s how you could implement it:

    public class GreaterThanAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string _otherProperty;
        public GreaterThanAttribute(string otherProperty)
        {
            _otherProperty = otherProperty;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _otherProperty);
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(_otherProperty);
            if (property == null)
            {
                return new ValidationResult(
                    string.Format(
                        CultureInfo.CurrentCulture, 
                        "unknown property {0}", 
                        _otherProperty
                    )
                );
            }
            var otherValue = (DateTime)property.GetValue(validationContext.ObjectInstance, null);
            var thisValue = (DateTime)value;
            if (thisValue <= otherValue)
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
    
            return null;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
            rule.ValidationType = "greaterthandate";
            rule.ValidationParameters["other"] = "*." + _otherProperty;
            yield return rule;
        }
    }
    

    and on the client side:

    (function ($) {
        var getModelPrefix = function (fieldName) {
            return fieldName.substr(0, fieldName.lastIndexOf('.') + 1);
        };
    
        var appendModelPrefix = function (value, prefix) {
            if (value.indexOf('*.') === 0) {
                value = value.replace('*.', prefix);
            }
            return value;
        };
    
        $.validator.unobtrusive.adapters.add('greaterthandate', ['other'], function (options) {
            var prefix = getModelPrefix(options.element.name),
                other = options.params.other,
                fullOtherName = appendModelPrefix(other, prefix),
                element = $(options.form).find(':input[name=' + fullOtherName + ']')[0];
    
            options.rules['greaterThanDate'] = element;
            if (options.message) {
                options.messages['greaterThanDate'] = options.message;
            }
        });
    
        $.validator.addMethod('greaterThanDate', function (value, element, params) {
            var otherDate = $(params).val();
            var thisDate = value;
    
            // TODO: put your custom date comparison implementation here between
            // the 2 values. Be careful here. Javascript date handling is culture dependent
            // so you might need to account for that when building your js Date instances
    
            return false;
        }, '');
    })(jQuery);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this (simplified) class: public class StarBuildParams { public int BaseNo { get;
I have a model (simplified for relevance) like this: public abstract class TitleCreateModel :
My simplified domain model looks something like this: public abstract class Entity<IdK> { public
I have a model like this defined... public class Product{ private long timestamp; //
Here is my data model (simplified), public class AddressBook { private List<Group> groups =
I think this explains my question well enough: public class Model { public static
Here is my simplified code: // Domain models public class Order { public int
This model is simplified, only used for demonstration. In my application got: Data public
Having this (simplified) XML: <?xml version=1.0 encoding=UTF-8?> <kml> <Document> <Placemark> <name>Poly 1</name> <Polygon> <coordinates>
I have a table like this (simplified): ID | Name | Parent --------------------------------- 1

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.