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 5999657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:34:59+00:00 2026-05-23T00:34:59+00:00

I am creating a day range validator using DataAnnotations, jQuery.validate and jquery.validate.unobtrusive. I’ve already

  • 0

I am creating a day range validator using DataAnnotations, jQuery.validate and jquery.validate.unobtrusive. I’ve already read the following:
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

http://weblogs.asp.net/mikaelsoderstrom/archive/2010/10/06/unobtrusive-validation-in-asp-net-mvc-3.aspx

and other but can’t post them (noob)

As well as most of the post on SO. I’m baning my head against a wall, any help could be rewardde with beer/food/code/etc 😉 Anyway here’s the code:

I have a model object with the following parameter:

[Display(Name = "Start date"), 
 DayRange(0, 5, ErrorMessage = "The Start Date must be between today and 5 days time.")]
public DateTime StartDate { get; set; }

DayRange is a custom attribute class :

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DayRangeAttribute : RangeAttribute, IClientValidatable
{
    private int _minimumDays;
    private int _maximumDays;

    public DayRangeAttribute(int minimumDays, int maximumDays) : base(minimumDays, maximumDays) 
    {
        _minimumDays = minimumDays;
        _maximumDays = maximumDays;
    }

    public override bool IsValid(object value)
    {
        var dateToBeTested = value as DateTime?;
        return dateToBeTested.HasValue && dateToBeTested.Value >= DateTime.Today.AddDays(_minimumDays) && dateToBeTested.Value <= DateTime.Today.AddDays(_maximumDays);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
                         {
                             ErrorMessage = this.ErrorMessage,
                             ValidationType = "dayrange"
                         };
        rule.ValidationParameters.Add("min", _minimumDays);
        rule.ValidationParameters.Add("max", _maximumDays);
        yield return rule;
    }
}

I have the following in my web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

I have have following JS trigger before the document is ready (have tried triggering it when the doc is ready too ):

jQuery.validator.addMethod('dayrange', function (value, element, param) {
    if (!value) return false;
    var now = Date();
    var dateValue = Date.parse(value);
    var minDate = now.setDate(now.getDate() - param.min);
    var maxDate = now.setDate(now.getDate() + param.max);

    return this.optional(element) && dateValue >= minDate && dateValue <= maxDate;
}, 'Must fall in range');

jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', 'minlength', 'maxlength', 'dayrange');

What am I doing wrong? Thanks in advance, Jol

  • 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-05-23T00:35:00+00:00Added an answer on May 23, 2026 at 12:35 am

    Solved! I forgot/didn’t understand that you have to pass jQuery itself into the function closure. Therefore the custom validator on the client side should look like this:

    $(function () {
        jQuery.validator.addMethod('dayRange', function (value, element, param) {
            if (!value) return false;
            var valueDateParts = value.split(param.seperator);
            var minDate = new Date();
            var maxDate = new Date();
            var now = new Date();
            var dateValue = new Date(valueDateParts[2],
                                (valueDateParts[1] - 1),
                                 valueDateParts[0],
                                 now.getHours(),
                                 now.getMinutes(),
                                 (now.getSeconds()+5));
    
            minDate.setDate(minDate.getDate() - parseInt(param.min));
            maxDate.setDate(maxDate.getDate() + parseInt(param.max));
    
        return dateValue >= minDate && dateValue <= maxDate;
    });
    
        jQuery.validator.unobtrusive.adapters.add('dayrange', ['min', 'max', 'dateseperator'], function (options) {
            var params = {
                min: options.params.min,
                max: options.params.max,
                seperator: options.params.dateseperator
            };
    
            options.rules['dayRange'] = params;
            if (options.message) {
                options.messages['dayRange'] = options.message;
            }
        });
    }(jQuery));
    

    I also change the way I add the adapter to unobtrusive so I can add additional properties. Never send to server-side dev to do a front-end engineers job 😉 Hope this helps someone.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm creating a day planner using jquery, draggable and droppable. When a job is
Right, so this is my first day using XML. I'm not creating the XML,
Good day! I am using Xcode 3.1.4 and iPhone SDK 2.2.1. I am creating
Good Day, I am creating a webpage that users login called index.html which POSTs
Good Day, I'm creating a VBScript function to return an array. But I want
I'm working on creating a map of Day Z (the game) with leaflet JS
I develop the site with Day CQ5 and was faced witha problem. I'm creating
compliment of the day. Based on the previous feedback received, After creating a Ticket
I'm working on creating a fireworks show in javascript for my last day of
I'm creating a date class in c++, which holds day, month and year variables

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.