Created
September 19, 2012 17:07
-
-
Save steff-mueller/3750826 to your computer and use it in GitHub Desktop.
ReactiveUI validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IValitated | |
{ | |
Dictionary<string, Func<string>> Validators { get; set; } | |
} | |
public class ValidatedReactiveObject : ReactiveObject, IValitated, IDataErrorInfo | |
{ | |
public Dictionary<string, Func<string>> Validators { get; set; } | |
public ValidatedReactiveObject() | |
{ | |
Validators = new Dictionary<string, Func<string>>(); | |
} | |
public string Error | |
{ | |
get { return null; } | |
} | |
public string this[string columnName] | |
{ | |
get { return Validators[columnName](); } | |
} | |
} | |
public static class ValidatonMixins | |
{ | |
public static void AddValidationRule<TObj, TRet>(this TObj obj, Expression<Func<TObj, TRet>> property, | |
Func<TRet, string> validateFn) where TObj : IValitated | |
{ | |
var getValueFn = property.Compile(); | |
var propName = simpleExpressionToPropertyName<TObj, TRet>(property); | |
if (obj.Validators == null) obj.Validators = new Dictionary<string, Func<string>>(); | |
obj.Validators.Add(propName, () => validateFn(getValueFn(obj))); | |
} | |
internal static string simpleExpressionToPropertyName<TObj, TRet>(Expression<Func<TObj, TRet>> Property) | |
{ | |
Contract.Requires(Property != null); | |
string prop_name = null; | |
try | |
{ | |
var prop_expr = Property.Body as MemberExpression; | |
if (prop_expr.Expression.NodeType != ExpressionType.Parameter) | |
{ | |
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty'"); | |
} | |
prop_name = prop_expr.Member.Name; | |
} | |
catch (NullReferenceException) | |
{ | |
throw new ArgumentException("Property expression must be of the form 'x => x.SomeProperty'"); | |
} | |
return prop_name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment