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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T17:58:01+00:00 2026-06-09T17:58:01+00:00

We are trying to create some custom validation with MVC 4 data annotations, the

  • 0

We are trying to create some custom validation with MVC 4 data annotations, the validation we are creating is kind of message prompts more than restrictive validation.
First of all we have created some custom validation classes inheriting from the ValidationAttribute
Class and overriding the IsValid() method to test the data and return an ValidationResult if not valid.
The view that displays this data has Partial views that use EditorTemplates to display razor generated data using our custom data annotations and many built in validation, all this is wrapped in a form like this

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))

Our requirements are to let the user post back the data and partially save the forms but prompt them on any invalid fields so are using the
CSS class on the form submit to allow postback like so

<input type="submit" value="Save" class="cancel"/>

All this is working fine but we have now requirements to display all the error messages on page load which I did not see to be a problem until I tried it…

I found a few examples that used jquery in the $(document).ready event that called the form valid methods as seen here

Manual form validation in MVC 3 and JQuery

but this did not seem to work for us the $(‘form’).Validate() does not seem to do anything the only call that seems to fire the forms validation is
$(‘form’).valid()
But this only seems to show the built in validation such as the [Required] attributes and the only way to get the custom validation messages to show is to use the submit button to post back the form.

There must be a way to get my custom data annotations to display the messages without posting back the page the first time right?
Any help would be greatly appreciated.

  • 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-09T17:58:03+00:00Added an answer on June 9, 2026 at 5:58 pm

    Ok so i have found a way to get the result i wanted although it was a little more work than I wanted/ imagined it would be.
    The stuff I was missing was I didn’t implament IClientValidatable in my custom validation class and had to add my custom validation to the jQuery Validator addmethod which I had tried but not with the IClientValidatable implamted in the custom validation class, I will quickly run through how to get this working im assuming you have all the jQuery stuff set up / included

    First create simple model that uses a custom validation attribute

    public class Person
    {
        [Required]
        [Display( Name="Name")]
        public string Name { get; set; }
        public int Age { get; set; }
    
        //Uses a custom data annotation that requires that at lease it self or the property name passed in the constructor are not empty
        [OneOfTwoRequired("Mobile")]
        public string Phone { get; set; }
        [OneOfTwoRequired("Phone")]
        public string Mobile { get; set; }
    }
    

    The custom validation class that uses reflection to get the property of the string name passed in to test with

    Note as of 15/08/2012 : if you are using MVC 4 you will need to of referenced System.web.mvc 3.0 for the use of IClientValidatable as ModelClientValidationRule does no seem to exist in MVC 4

    public class OneOfTwoRequired : ValidationAttribute, IClientValidatable
        {
            private const string defaultErrorMessage = "{0} or {1} is required.";
    
            private string otherProperty;
    
            public OneOfTwoRequired(string otherProperty)
                : base(defaultErrorMessage)
            {
                if (string.IsNullOrEmpty(otherProperty))
                {
                    throw new ArgumentNullException("otherProperty");
                }
    
                this.otherProperty = otherProperty;
            }
    
            public override string FormatErrorMessage(string name)
            {
                return string.Format(ErrorMessageString, name, otherProperty);
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty);
    
                if (otherPropertyInfo == null)
                {
                    return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty));
                }
    
                var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
    
                if (otherPropertyValue == null && value == null)
                {
                    return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
                }
    
                return ValidationResult.Success;
            }
            public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                yield return new ModelClientValidationRule
                {
                    ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                    //This is the name of the method aaded to the jQuery validator method (must be lower case)
                    ValidationType = "oneoftworequired"
                };
    
            }
        }
    

    Add this to the View or partialview, you must make sure this is not in a $(document).ready method

        jQuery.validator.addMethod("oneoftworequired", function (value, element, param) {
            if ($('#Phone).val() == '' && $('#Mobile).val() == '')
                return false;
            else
                return true;
        });
    
        jQuery.validator.unobtrusive.adapters.addBool("oneoftworequired");
    

    the jQuery validator stuff only seems to be needed if you want to validate the form without posting back or on initial page load and to do that you just call $(‘form’).valid()

    Hope this helps somebody 🙂

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

Sidebar

Related Questions

I have an MVC 3 app I am trying to create some custom authentication
I'm trying to create a form with some custom data attributes on the inputs:
I'm trying to create a MIME filter to do some custom processing of resources
I'm trying to create a custom form input that utilizes some images, it should
I am trying to create some charts of data (eg http://www.amibroker.com/ ). Is there
I am trying to create some dynamic html out of some data from db.
I am trying to create some custom templated widgets with dijit.layout objects (BorderContainer, ContentPane)
I am trying to create a custom HTML Helper that encapsulates some presentation logic
I'm trying to create a controller for a custom complex object but have some
I am trying to perform some custom validation with play framework but I don't

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.