Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Reflection;
- namespace Core {
- /// <summary>
- /// Helper class used to validate components the use the 'System.ComponentModel.DataAnnotations' validation attributes
- /// </summary>
- public class ValidationHelper {
- /// <summary>
- /// Validates the component's "Required" and "StringLength" Attributes and returns a dictionary with the Property Name as the key and the error message as the value;
- /// Note: If a propery has more than one 'error message' the error message will be delimeted by a NewLine
- /// </summary>
- /// <param name="component">The object to validate with "Required" and "StringLength" Attributes</param>
- /// <param name="errors">A dictionary used to add Property Name as the key and the error message as the value</param>
- public static void AppendValidationErrors(object component,Dictionary<string,string> errors) {
- //Test for required fields
- var requiredProps = TypeHelper.GetAttributes<RequiredAttribute>(component);
- foreach(MemberInfo propname in requiredProps.Keys) {
- var att = requiredProps[propname];
- object propvalue = TypeHelper.GetValue(component,propname.Name);
- if(!att.IsValid(propvalue)) {
- string errmsg = att.ErrorMessage;
- if(errmsg.IsNullOrEmptyTrim())
- errmsg = propname + " is required";
- //append or add the error message for the propertyname
- if(errors.ContainsKey(propname.Name))
- errors[propname.Name] += "\r\n" + errmsg;
- else
- errors.Add(propname.Name,errmsg);
- }
- }
- //Test for string lengths either max or min
- var stringLengthProps = TypeHelper.GetAttributes<StringLengthAttribute>(component);
- foreach(MemberInfo propname in stringLengthProps.Keys) {
- var att = stringLengthProps[propname];
- var propvalue = TypeHelper.GetValue(component,propname.Name);
- if(!att.IsValid(propvalue)) {
- string errmsg = att.ErrorMessage;
- if(errmsg.IsNullOrEmptyTrim()) {
- if(att.MinimumLength == 0) {
- errmsg = propname + " must be not greater than {0} characters".FormatString(att.MaximumLength);
- }
- else if(att.MaximumLength > 0 && att.MinimumLength > 0) {
- errmsg = propname + " must be between {0} and {1} characters".FormatString(att.MinimumLength,att.MaximumLength);
- }
- else
- errmsg = propname + " string length is invalid";
- }
- //append or add the error message for the propertyname
- if(errors.ContainsKey(propname.Name))
- errors[propname.Name] += "\r\n" + errmsg;
- else
- errors.Add(propname.Name,errmsg);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment