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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T07:37:09+00:00 2026-05-27T07:37:09+00:00

I found a RequiredIfAttribute on the internet which I modified to RequiredNotIf. The attribute

  • 0

I found a RequiredIfAttribute on the internet which I modified to RequiredNotIf. The attribute can be used like this.

[RequiredNotIf("LastName", null, ErrorMessage = "You must fill this.")]
public string FirstName { get; set; }

[RequiredNotIf("FirstName", null, ErrorMessage = "You must fill this")]
public string LastName { get; set; }

And the source code to the attribute…

[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)]
public class RequiredNotIfAttribute : RequiredAttribute, IClientValidatable
{
    private string OtherProperty { get; set; }
    private object Condition { get; set; }

    public RequiredNotIfAttribute(string otherProperty, object condition)
    {
        OtherProperty = otherProperty;
        Condition = condition;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(OtherProperty);
        if (property == null)
        {
            return new ValidationResult(String.Format("Property {0} not found.", OtherProperty));
        }

        var propertyValue = property.GetValue(validationContext.ObjectInstance, null);
        var conditionIsMet = !Equals(propertyValue, Condition);
        return conditionIsMet ? base.IsValid(value, validationContext) : null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
            ValidationType = "requiredif",
        };

        var depProp = BuildDependentPropertyId(metadata, context as ViewContext);

        var targetValue = (Condition ?? "").ToString();
        if (Condition != null && Condition is bool)
        {
            targetValue = targetValue.ToLower();
        }

        rule.ValidationParameters.Add("otherproperty", depProp);
        rule.ValidationParameters.Add("condition", targetValue);

        yield return rule;
    }

    private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
    {
        var depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(OtherProperty);
        var thisField = metadata.PropertyName + "_";
        if (depProp.StartsWith(thisField))
        {
            depProp = depProp.Substring(thisField.Length);
        }
        return depProp;
    }
}

The drawback with this – as I see it – is the magic string in the attribute “header”. How can I get rid of it?

  • 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-27T07:37:10+00:00Added an answer on May 27, 2026 at 7:37 am

    You can’t get rid of it because attributes are metadata and values must be known at compile time. If you want to do more advanced validation without magic strings I would very strongly recommend you FluentValidation.NET. Performing validation with attributes in a declarative manner is very limiting IMHO. Just look at the quantity of source code you have to write for something as standard and easy as RequiredIf or RequiredNotIf. I don’t know what the designers of the framework were thinking when they choose Data Annotations for validation. It’s just ridiculous. Maybe in the future they will enrich it and allow for more complex scenarios but until then I stick with FV.

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

Sidebar

Related Questions

found this regex: insert every 10 characters: $text = preg_replace(|(.{10})|u, \${1}. , $text); can
Found a question which already explains this - How to sort an array of
Found out about this cool jQuery countdown which is initialized as such: <script type="text/javascript">
Found this which may explain some of my problems - MSDN Post I have
Found this question here And I can't understand, why on first case it prints
Found this recently, but can't for the life of me figure out how the
Found this Reboot Vista.vbs script on a number of forums. Seems like the whole
Found this bit of code in FrogCms function isWritable($file=null) { $perms = fileperms($file); if
Found this: Sub SurroundWithAppendTag() DTE.ActiveDocument.Selection.Text = .Append( + DTE.ActiveDocument.Selection.Text + ) End Sub But
Found this rather strange bug in IE8; element.style.top is limited to 1342177 pixels. Even

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.