public static bool StringMaxLength(object target, ValidationRuleArgs e) { MaxLengthRuleArgs args = e as MaxLengthRuleArgs; if (args == null) { throw new ArgumentException("Invalid ValidationRuleArgs. e must be of type MaxLengthRuleArgs."); } int maxLength = args.MaxLength; PropertyInfo property = target.GetType().GetProperty(e.PropertyName); if (property == null) { throw new ArgumentException(string.Format("Property \"{0}\" not found on object \"{1}\"", e.PropertyName, target.GetType().ToString())); } if (property.PropertyType != typeof(string)) { throw new ArgumentException(string.Format("Property \"{0}\" is not of type String.", e.PropertyName)); } string text = (string)property.GetValue(target, null); if (!string.IsNullOrEmpty(text) && (text.Length > maxLength)) { if (string.IsNullOrEmpty(e.Description)) { e.Description = string.Format("{0} can not exceed {1} characters", e.PropertyName, maxLength.ToString()); } return(false); } return(true); }
/// <summary> /// Rule ensuring a String value doesn't exceed /// a specified length. /// </summary> /// <param name="target">Object containing the data to validate.</param> /// <param name="e"><see cref="ValidationRuleArgs"/> containing the information about the object to be validated.</param> /// <returns>False if the rule is broken; true otherwise.</returns> /// <remarks> /// This implementation uses late binding, and will only work /// against String property values. /// </remarks> public static bool StringMaxLength(object target, ValidationRuleArgs e) { MaxLengthRuleArgs args = e as MaxLengthRuleArgs; if (args != null) { int max = args.MaxLength; PropertyInfo p = target.GetType().GetProperty(e.PropertyName); if (p != null) { if (p.PropertyType == typeof(string)) { string value = (string)p.GetValue(target, null); if (!String.IsNullOrEmpty(value) && (value.Length > max)) { if (string.IsNullOrEmpty(e.Description)) { e.Description = String.Format("{0} can not exceed {1} characters", e.FriendlyName, max.ToString()); } return(false); } return(true); } else { throw new ArgumentException(string.Format("Property \"{0}\" is not of type String.", e.PropertyName)); } } else { throw new ArgumentException(string.Format("Property \"{0}\" not found on object \"{1}\"", e.PropertyName, target.GetType().ToString())); } } else { throw new ArgumentException("Invalid ValidationRuleArgs. e must be of type MaxLengthRuleArgs."); } }