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

  • Home
  • SEARCH
  • 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 6712449
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T08:15:40+00:00 2026-05-26T08:15:40+00:00

I have a value on my model, that must fall within the range of

  • 0

I have a value on my model, that must fall within the range of two other values on my model.

For example:

public class RangeValidationSampleModel
{
    int Value { get; set; }

    int MinValue { get; set; }

    int MaxValue { get; set; }
}

Of course, I can’t pass these Min/MaxValues into my DataAnnotations attributes, as they have to be constant values.

I’m sure I need to build my own validation attribute, but I haven’t done this much and can’t wrap my mind around how it should work.

I’ve searched for about an hour, and have seen all sorts of solutions for building custom validation, but can’t find anything to solve this particular problem using MVC3 unobtrusive validation.

  • 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-26T08:15:40+00:00Added an answer on May 26, 2026 at 8:15 am

    You could write a custom validation attribute for this purpose:

    public class DynamicRangeValidator : ValidationAttribute, IClientValidatable
    {
        private readonly string _minPropertyName;
        private readonly string _maxPropertyName;
        public DynamicRangeValidator(string minPropertyName, string maxPropertyName)
        {
            _minPropertyName = minPropertyName;
            _maxPropertyName = maxPropertyName;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var minProperty = validationContext.ObjectType.GetProperty(_minPropertyName);
            var maxProperty = validationContext.ObjectType.GetProperty(_maxPropertyName);
            if (minProperty == null)
            {
                return new ValidationResult(string.Format("Unknown property {0}", _minPropertyName));
            }
            if (maxProperty == null)
            {
                return new ValidationResult(string.Format("Unknown property {0}", _maxPropertyName));
            }
    
            int minValue = (int)minProperty.GetValue(validationContext.ObjectInstance, null);
            int maxValue = (int)maxProperty.GetValue(validationContext.ObjectInstance, null);
            int currentValue = (int)value;
            if (currentValue <= minValue || currentValue >= maxValue)
            {
                return new ValidationResult(
                    string.Format(
                        ErrorMessage, 
                        minValue,
                        maxValue
                    )
                );
            }
    
            return null;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "dynamicrange",
                ErrorMessage = this.ErrorMessage,
            };
            rule.ValidationParameters["minvalueproperty"] = _minPropertyName;
            rule.ValidationParameters["maxvalueproperty"] = _maxPropertyName;
            yield return rule;
        }
    }
    

    and then decorate your view model with it:

    public class RangeValidationSampleModel
    {
        [DynamicRangeValidator("MinValue", "MaxValue", ErrorMessage = "Value must be between {0} and {1}")]
        public int Value { get; set; }
        public int MinValue { get; set; }
        public int MaxValue { get; set; }
    }
    

    then you could have a controller serving a view:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new RangeValidationSampleModel
            {
                Value = 5,
                MinValue = 6,
                MaxValue = 8
            });
        }
    
        [HttpPost]
        public ActionResult Index(RangeValidationSampleModel model)
        {
            return View(model);
        }
    }
    

    and a view of course:

    @model RangeValidationSampleModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $.validator.unobtrusive.adapters.add('dynamicrange', ['minvalueproperty', 'maxvalueproperty'],
            function (options) {
                options.rules['dynamicrange'] = options.params;
                if (options.message != null) {
                    $.validator.messages.dynamicrange = options.message;
                }
            }
        );
    
        $.validator.addMethod('dynamicrange', function (value, element, params) {
            var minValue = parseInt($('input[name="' + params.minvalueproperty + '"]').val(), 10);
            var maxValue = parseInt($('input[name="' + params.maxvalueproperty + '"]').val(), 10);
            var currentValue = parseInt(value, 10);
            if (isNaN(minValue) || isNaN(maxValue) || isNaN(currentValue) || minValue >= currentValue || currentValue >= maxValue) {
                var message = $(element).attr('data-val-dynamicrange');
                $.validator.messages.dynamicrange = $.validator.format(message, minValue, maxValue);
                return false;
            }
            return true;
        }, '');
    </script>
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Value)
            @Html.EditorFor(x => x.Value)
            @Html.ValidationMessageFor(x => x.Value)
        </div>
        <div>
            @Html.LabelFor(x => x.MinValue)
            @Html.EditorFor(x => x.MinValue)
        </div>
        <div>
            @Html.LabelFor(x => x.MaxValue)
            @Html.EditorFor(x => x.MaxValue)
        </div>
        <button type="submit">OK</button>
    }
    

    Obviously the custom adapter registration should be performed in an external javascript file to avoid polluting the view but for the purpose and conciseness of this post I have put it inside the view.

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

Sidebar

Related Questions

I have a property within a data model, that property must have a value
I have two fields on an MVC3 form that must represent the same value.
I have a model that contains a foreign key value, then in the form
I have a rails model that validates uniqueness of 2 form values. If these
in a Model I have a CharField with choices: class MyModel(models.Model): THE_CHOICES=( ('val',_(u'Value Description')),
I have a two model classes which have relationship of one to many. public
I have a property on my view model that is a custom class with
I have a basic ActiveRecord model in which i have two fields that i
I have a simple question. I have a model that looks like this: public
I have a model that must be in one of the following mutually exclusive

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.