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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T10:36:41+00:00 2026-05-23T10:36:41+00:00

I read on some post, but cant find it now that in MVC 3

  • 0

I read on some post, but cant find it now that in MVC 3 it was not really needed to create a Validator, only the Attribute. Is this true? I do say I find it confusing that the attribute has the IClientValidatable on it. So what does the DataAnnotationsModelValidator class do if the annotation has the client side script name (IClientValidatable), and the ability to validate (ValidationAttribute IsValid)?

It would be really nice if I didnt have to register the Attribute with the Validator in the global. Can this be done? Did I read some bad advise?

EDIT: Interestingly enough I just tested it by excluding the validator, put all the logic in IsValid and it works great. I guess the only thing that might be missing would be the controller context, but I am not sure that is useful in validation. The IsValid has ValidationContext which has ServiceContainer if I needed a service. Any real disadvantage I am not picking up on here?

EDIT 2:
I will start with a validator from this example: http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

The Attribute:

public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public RequiredIfAttribute(string dependentProperty, object targetValue)
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule modelClientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "requiredifattribute"
        };
        modelClientValidationRule.ValidationParameters.Add("requiredifattribute", DependentProperty);
        yield return modelClientValidationRule;
    }
}

The Validator:

public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
    public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
        : base(metadata, context, attribute)
    {
    }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        return base.GetClientValidationRules();
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        var field = Metadata.ContainerType.GetProperty(Attribute.DependentProperty);
        if (field != null)
        {
            var value = field.GetValue(container, null);
            if ((value == null && Attribute.TargetValue == null) ||
                (value.Equals(Attribute.TargetValue)))
            {
                if (!Attribute.IsValid(Metadata.Model))
                    yield return new ModelValidationResult { Message = ErrorMessage };
            }
        }
    }
}

With the current code above, I need to register in the Global.asax.cs file:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));

But if I move everything into just the attribute, I dont have to register it:

public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public RequiredIfAttribute(string dependentProperty, object targetValue)
    {
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
        if (field != null)
        {
            var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
            if ((dependentValue == null && TargetValue == null) ||
                (dependentValue.Equals(TargetValue)))
            {
                if (!innerAttribute.IsValid(value))
                    return new ValidationResult(ErrorMessage);
            }
        }
        return ValidationResult.Success;
    }

    public System.Collections.Generic.IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule modelClientValidationRule = new ModelClientValidationRule()
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "requiredifattribute"
        };
        modelClientValidationRule.ValidationParameters.Add("requiredifattribute", DependentProperty);
        yield return modelClientValidationRule;
    }
}

Is there an problem with the last bit of code replacing all of the other code? Why would I keep the validator class?

  • 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-23T10:36:41+00:00Added an answer on May 23, 2026 at 10:36 am

    CrazyDart,

    The IClientValidatable interface was added in MVC3.

    Your second example shows a valid use of this new interface. You are correct that it does not have to be registered, and it will provide the necessary client side rules for validation, as well as doing the necessary server side validation.

    Go ahead, enjoy it.

    counsellorben

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

Sidebar

Related Questions

I've read through some of the post on here about closures and currying but
I read some source code of ZenTest but didn't find where it is implemented.
I read some microsoft articles.They explained that WCF uses DataContractSerializer for serialization.But the articles
Having read an existing post on stackoverflow and done some reading around on the
I read some properties from an xml file, amongst which is a string that
I read some articles about Comet tech. All of them mentioned that the long-life
I read some of the discussion in this question and thought to myself that
I read some tutorials concerning Makefiles but for me it is still unclear for
I've read a few other questions that seem similar but I'm still very confused,
Maybe the solution is obvious, but I cant seem to find a good one.

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.