Skip to content

Expression Lamda #1

@tgiachi

Description

@tgiachi

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));
                }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions