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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T19:13:13+00:00 2026-05-24T19:13:13+00:00

I have a ViewModel that holds Date, Hour and minute as a string, each

  • 0

I have a ViewModel that holds Date, Hour and minute as a string, each of these have a textbox for entering values into them, what I then want is a custom validator that ensures that if a value is entered into one of the fields then the rest have to be filled out as well, otherwise they can be empty, its all or nothing!

I have made a little test project here, but its not workign the way it should, I have followed http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2 but I think my issues are clientside, as I cant see any value on the Params if I do a breakpoint in chrome.

The View:

@model validationproject.Models.DateTimeViewModel

@{
    ViewBag.Title = "ViewPage1";
}

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="../../Scripts/Validators.js" type="text/javascript"></script>

<h2>ViewPage1</h2>
@using (Ajax.BeginForm("CreateDateTime", "Home", new {}, new AjaxOptions {HttpMethod = "Post"}))
{
    <span>
    @Html.TextBoxFor(model => model.Date, new {@Id = "date"}) 

    @Html.TextBoxFor(model => model.Hour, new {@Id = "hour"})

    @Html.TextBoxFor(model => model.Minute, new {@Id = "minute"})

    @Html.ValidationMessageFor(model => model.Date)
    @Html.ValidationMessageFor(model => model.Hour)
    @Html.ValidationMessageFor(model => model.Minute)
    </span>
}  

JQuery validator file

$.validator.unobtrusive.adapters.add(
            'fulldaterequired',
            ['part1', 'part2'],
            function (options) {
                options.rules['fulldaterequiredcheck'] = options.params;
                options.messages['fulldaterequiredcheck'] = options.message;
            }
        );

$.validator.addMethod(
        'fulldaterequiredcheck',
        function (value, element, params) {

            if (!value && (params['otherproperty1'] || params['otherproperty2'])) {
                return false;
            }
            return true;
        }
    );

My Viewmodel

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace validationproject.Models
{
    public class DateTimeViewModel  
    {
        [Display(Name = "Date")]
        [FullDateRequired(("Hour"), ("Minute"))]
        public string Date { get; set; }

        [Display(Name = "Hour")]
        [FullDateRequired(("Minute"), ("Date"))]
        public string Hour { get; set; }

        [Display(Name = "Minute")]
        [FullDateRequired(("Hour"), ("Date"))]
        public string Minute { get; set; }
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class FullDateRequired : ValidationAttribute, IClientValidatable
    {
        private const string DefaultErrorMessage = "{0} is required.";
        public string OtherProperty1 { get; private set; }
        public string OtherProperty2 { get; private set; }
        public FullDateRequired(string otherProperty1, string otherProperty2)
            : base(DefaultErrorMessage)
        {
            OtherProperty1 = otherProperty1;
            OtherProperty2 = otherProperty2;
        }
        public override string FormatErrorMessage(string name)
        {
            return string.Format(ErrorMessageString, name);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var otherProperty1 = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty1);
            var otherProperty2 = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty2);
            var otherProperty1Value = string.IsNullOrEmpty((string)otherProperty1.GetValue(validationContext.ObjectInstance, null));
            var otherProperty2Value = string.IsNullOrEmpty((string)otherProperty2.GetValue(validationContext.ObjectInstance, null));

            if (string.IsNullOrEmpty((string)value) && (!otherProperty1Value || !otherProperty2Value))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return ValidationResult.Success;
        }
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var clientValidationRule = new ModelClientValidationRule()
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "fulldaterequired"
            };
            clientValidationRule.ValidationParameters.Add("otherproperty1", OtherProperty1);
            clientValidationRule.ValidationParameters.Add("otherproperty2", OtherProperty2);
            return new[] { clientValidationRule };
        }
    }
}
  • 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-24T19:13:14+00:00Added an answer on May 24, 2026 at 7:13 pm

    Your javascript contains ‘part1’ and ‘part2’ which should be ‘otherproperty1’ and ‘otherproperty2’ as defined in your viewmodel. The correct script should be:

    $.validator.unobtrusive.adapters.add(
            'fulldaterequired',
            ['otherproperty1', 'otherproperty2'],
            function (options) {
                options.rules['fulldaterequiredcheck'] = options.params;
                options.messages['fulldaterequiredcheck'] = options.message;
            }
        );
    
            $.validator.addMethod(
        'fulldaterequiredcheck',
        function (value, element, params) {
            if (value == '' && ($('#' + params['otherproperty1']).val() != '' || $('#' + params['otherproperty2']).val() != '')) {
                return false;
            }
            return true;
        }
    );
    

    Add this to your view (inside the form) to show errormessages when you press the submit button:

        @Html.ValidationMessageFor(model => model.Date)
        @Html.ValidationMessageFor(model => model.Hour)
        @Html.ValidationMessageFor(model => model.Minute)
    
        <input type="submit" />
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a textbox that i am binding to the viewmodel's string property. The
I have a ViewModel class that implements the IDataErrorInfo Interface . In each property's
I have a viewmodel that contains a product and SelectList of categories. public class
I have a viewmodel that contains a number of properties, a SelectList, and an
I have a ViewModel class that contains a list of points, and I am
I have a ViewModel (AbstractContextMenu) that represents my context menu (IContextMenu), and I bind
The default MVVP I have seen has multiple ViewModel objects that are rendered through
I have a object that implements the IEditableObject interface exposed on a viewmodel bound
I have a class that roughly looks like this: public class ViewModel { public
I have a ComboBox that has the SelectedItem bound to the ViewModel. <ComboBox SelectedItem={Binding

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.