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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T06:49:36+00:00 2026-05-11T06:49:36+00:00

So I have a simple validation rule pattern that I’m using to do validation

  • 0

So I have a simple validation rule pattern that I’m using to do validation on entity objects. Here is my ValidationRule class:

public class ValidationRule {      public Func<object, bool> Rule { get; set; }     public string ErrorMessage { get; set; }      public ValidationRule(string errorMessage, Func<object, bool> rule) {          Rule = rule;         ErrorMessage = errorMessage;     }      public bool IsValid(object obj) {         return Rule(obj);     } } 

I have a base class for my entity objects that encapsulate the methods to perform validation that looks like this:

public abstract class ModelBase {      private List<ValidationRule> _validationRules;     public List<ValidationRule> ValidationRules {         get {             if (_validationRules == null)                 _validationRules = new List<ValidationRule>();             return _validationRules;         }         set { _validationRules = value; }     }      public ValidationResult Validate() {         var result = new ValidationResult();         rules.ForEach(r => {             if (!r.IsValid(this))                 result.Errors.Add(                     new ValidationError(r.ErrorMessage, r.PropertyName));                          });         return result;     } } 

And now here’s the real problem I’m trying to solve. When I create a new class that inherits from ModelBase adding validation rules is a little awkward. For example:

public class Client : ModelBase {      public int ID{ get; set; }     public string Name { get; set; }     public Address MailingAddress { get; set; }      public Client() {         CreateValidationRules();     }      private void CreateValidationRules() {          ValidationRules.Add(new ValidationRule('Client 'Name' is required.',             c => !string.IsNullOrEmpty(((Client)c).Name)));     } } 

Notice where I’m creating the validation rules list. Inside the lambda expression I have to cast ‘c’ to ‘Client’ because my rule is essentially Func<object, bool>. I’ve tried many ways to make this generic by doing something like ValidationRule<Client> but I always run into problems with calling Validate() in the ModelBase class. Any ideas on how to get around this casting?

  • 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. 2026-05-11T06:49:37+00:00Added an answer on May 11, 2026 at 6:49 am

    You can make the ValidationRule class generic, but leave the parameter for the IsValid method as object and do the casting in the method. That way you get the generics without having to make ModelBase generic also.

    You also need an interface for the ModelBase to be able to keep a list of validation rules without knowing their actual type. Then just change the type of the list and the property in ModelBase to IValidationRule.

    (Note: You can use a private setter on the properties to make them read-only.)

    public Interface IValidationRule {    bool IsValid(object); }  public class ValidationRule<T> : IValidationRule {      public Func<T, bool> Rule { get; private set; }     public string ErrorMessage { get; private set; }      public ValidationRule(string errorMessage, Func<object, bool> rule) {          Rule = rule;         ErrorMessage = errorMessage;     }      public bool IsValid(object obj) {         return Rule((T)obj);     } } 

    Now, the type of the parameter in the lamda expression is the generic type, so you don’t have to cast it:

    ValidationRules.Add(       new ValidationRule<Client>(            'Client 'Name' is required.',            c => !string.IsNullOrEmpty(c.Name)       )  ); 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 99k
  • Answers 99k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer To get the WAR file in your new project just… May 11, 2026 at 7:47 pm
  • Editorial Team
    Editorial Team added an answer I found a smart solution to generate NSInvocation objects. May 11, 2026 at 7:47 pm
  • Editorial Team
    Editorial Team added an answer Simple vector graphics apps can do a pretty good job… May 11, 2026 at 7:47 pm

Related Questions

So I have a simple validation rule pattern that I'm using to do validation
I have a LINQ partial class: public partial class resp { public IEnumerable<RuleViolation> GetRuleViolations()
I have a WPF window that uses validation. I created an error template that
I have a very simple WPF application in which I am using data binding
I have a simple model that is defined as: class Article(models.Model): slug = models.SlugField(max_length=50,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.