Question

I currently have to validate custom Field Objects for my application. Simply put, each Field object consists of information about the validation for the field, as well as the value of the field. I am validating fields in bulk, so currently, I have a validation class, that has a method for each validation. For required fields, it looks something like this:

      private void RequiredFields()
      {
            foreach (Field field in allFields)
            {
                if ((field.Required == true) && (field.Value == string.Empty))
                {
                    field.isValid = false;
                }
            }
      }

Now my problem is that I feel like I should a layer of abstraction to the validation, so instead of saying:

if ((field.Required == true) && (field.Value == string.Empty))

... I would add a validation class, to accept the values and turn it into this:

if (!validater.RequiredFields(field.Required, field.Value))

If I were to do this, it would allow me to reuse the validation class without use of the field objects, and it would also allow better unit testing... However, it seems like and unnecessary layer of abstraction and also somewhat repetitive... Keep in mind, this is the most simple of all the validation.

Suggestions?

Was it helpful?

Solution

Why not have make Field objects responsible for their own validation?

class Field
{
    public bool Required { get; }
    public string Value { get; set; }

    // assuming that this method is virtual here
    // if different Fields have different validation logic
    // they should probably be separate classes anyhow and
    // simply implement a common interface of inherit from a common base class.
    public override bool IsValid
    {
        get { return Required && Value != String.Empty; }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top