Skip to content

Instantly share code, notes, and snippets.

@ericnewton76
Last active August 29, 2015 13:57
Show Gist options
  • Save ericnewton76/9667051 to your computer and use it in GitHub Desktop.
Save ericnewton76/9667051 to your computer and use it in GitHub Desktop.
Builds a complete list of items that pass or fail validation checks.
using System;
using System.Collections.Generic;
public class ValidateCheckBuilder
{
private List<ValidationCheck> _validationchecks = new List<ValidationCheck>();
public IEnumerable<ValidationCheck> ValidationChecks { get { return this._validationchecks; } }
private bool? _allValid;
public bool AllValid { get { return _allValid.GetValueOrDefault(); } }
private string _name;
private string _message;
private object[] _messageFormatArgs;
public ValidateCheckBuilder Start(string name)
{
this._name = name;
return this;
}
public ValidateCheckBuilder Message(string format, params object[] args)
{
_message = format;
_messageFormatArgs = args;
return this;
}
public ValidationCheck TestValid(Func<bool> validationFunction)
{
bool isValid;
try
{
isValid = validationFunction();
}
catch { isValid = false; }
if (_allValid == null)
_allValid = isValid;
else
_allValid &= isValid;
//build message
string message = _message;
if (_messageFormatArgs != null)
message = string.Format(_message, _messageFormatArgs);
ValidationCheck instance = new ValidationCheck(isValid, this._name, message);
this._validationchecks.Add(instance);
return instance;
}
public ValidationCheck Add(string name, string message, Func<bool> validatedFunction)
{
bool isValid;
try
{
isValid = validatedFunction();
}
catch { isValid = false; }
return new ValidationCheck(isValid, name, message);
}
}
public class ValidationCheck
{
public ValidationCheck(bool isvalid, string name, string message)
{
this.IsValid = isvalid;
this.Name = name;
this._message = message;
}
public ValidationCheck(bool isvalid, string name, string format, object[] formatArgs)
{
this.IsValid = isvalid;
this.Name = name;
this._message = format;
this._formatArgs = formatArgs;
}
private string _message;
private object[] _formatArgs;
public bool IsValid { get; private set; }
public string Name { get; private set; }
public string Message
{
get
{
if (_formatArgs == null)
return _message;
else
return string.Format(_message, _formatArgs);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment