Caliburn.Micro.Validation icon indicating copy to clipboard operation
Caliburn.Micro.Validation copied to clipboard

Expression Lamda

Open tgiachi opened this issue 10 years ago • 1 comments

Is possibile to scan the [MaxLength] and [Require] attribute from object and build validation rule?

protected void AutoBuildValidationRulesForObject<T>(T obj, string variableName)
        {


            foreach (var field in typeof(T).GetProperties())
            {
var maxLenghtAttr = (MaxLengthAttribute)field.GetCustomAttributes(typeof(MaxLengthAttribute), true).ToList().FirstOrDefault();
                var required = (ValidationAttribute)field.GetCustomAttributes(typeof(RequiredAttribute), true).ToList().FirstOrDefault();

                if (maxLenghtAttr != null)
                {


                    var variable = Expression.Variable(typeof(T), variableName);
                    var pe = Expression.Property(variable, typeof(T), field.Name);
                    var left = Expression.Property(pe, typeof(string).GetProperty("Length"));
                    var right = Expression.Constant(maxLenghtAttr.Length, typeof(int));
                    var e2 = Expression.LessThanOrEqual(left, right);
                    var predicate = Expression.Lambda<Func<bool>>(e2);
                    if (required != null)
                        AddValidationRule(() => variable).Condition(predicate).Message(required.ErrorMessage);
                    else
                        AddValidationRule(() => variable).Condition(predicate).Message(string.Format("{0} Must be Less then of {1}", field.Name, maxLenghtAttr.Length));
                }

tgiachi avatar May 21 '15 15:05 tgiachi

Sorry, I just have seen your message (possible I accidentally skipped the notification). Is the question is still actual? Anyway feel free to fork my project and make required code modifications.

AIexandr avatar Jun 29 '15 17:06 AIexandr