public void ApplyRuleFor <TProperty>(Expression <Func <TModel, TProperty> > expression, AppValidationAttribute validationAttribute) { var errorMsg = validationAttribute.ErrorMessage; switch (validationAttribute) { case RequiredAttribute requiredAttribute: { var requiredRule = RuleFor(expression).NotEmpty().WithMessage("This field is required."); SetRuleErrorMessage(requiredRule, errorMsg); break; } case StringLengthAttribute stringLengthAttribute when expression.ReturnType == typeof(string): var stringLengthMinLengthRule = RuleFor(expression as Expression <Func <TModel, string> >) .MinimumLength(stringLengthAttribute.MinimumLength); SetRuleErrorMessage(stringLengthMinLengthRule, errorMsg); var stringLengthMaxLengthRule = RuleFor(expression as Expression <Func <TModel, string> >) .MaximumLength(stringLengthAttribute.MaximumLength); SetRuleErrorMessage(stringLengthMaxLengthRule, errorMsg); break; } }
private void ApplyRuleForProperty(PropertyInfo property, AppValidationAttribute validationAttribute) { var methodInfo = GetType().GetMethod(nameof(ApplyRuleFor)); var argumentTypes = new[] { property.PropertyType }; var genericMethod = methodInfo.MakeGenericMethod(argumentTypes); var propertyExpression = ExpressionHelper.CreateMemberExpressionForProperty <TModel>(property); genericMethod.Invoke(this, new[] { propertyExpression, validationAttribute }); }