public static void Init(IValidateable o, TabPage p) { foreach (PropertyInfo pr in o.GetType().GetProperties()) { PropertyInfo pi = o.GetType().GetProperty(pr.Name, typeof(string)); if (pi != null) { pi.SetValue(o, p.Controls[pr.Name].Text); } } }
public static void ParseNValidate(IValidateable o, List <ValidationResult> errors) { //List<ValidationAttribute> atts = new List<ValidationAttribute>(); //atts.Add(new RegularExpressionAttribute()) o.GetType().GetProperties().Where(el => Attribute.IsDefined(el, typeof(StringLengthAttribute))) .ToList().ForEach(pr => { TryValidateValue(o, pr.Name, o.GetType().GetProperty(pr.Name).GetValue(o, null), errors); }); }
public static IEnumerable <string> Validate(this IValidateable obj) { List <string> errors = new List <string>(); IEnumerable <PropertyInfo> properties = obj.GetType().GetProperties(); foreach (PropertyInfo property in properties) { DisplayAttribute nameAttribute = property.GetCustomAttribute <DisplayAttribute>(); string propName = (nameAttribute == null) ? property.Name : nameAttribute.Name; object value = property.GetValue(obj); IEnumerable <ValidationAttribute> attributes = property.GetCustomAttributes <ValidationAttribute>(true); foreach (ValidationAttribute attribute in attributes) { if (!attribute.IsValid(value)) { errors.Add(attribute.FormatErrorMessage(propName)); } } } return(errors); }
private static void AddRequiredFieldMissingMessage(ValidationResult result, FormFieldAttribute attr, string propertyName, IValidateable entity) { if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null) { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource); var validationMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null); result.AddUserError(validationMessage, entity.GetType().Name); } else { var propertyLabel = GetLabel(attr); if (String.IsNullOrEmpty(propertyLabel)) { result.AddSystemError(Resources.ValidationResource.Entity_Header_Null_System.Replace("[NAME]", propertyName), entity.GetType().Name); } else { result.AddUserError(Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel), entity.GetType().Name); } } }
private static void ValidateId(ValidationResult result, IValidateable entity) { if (entity is IIDEntity) { var idModel = entity as IIDEntity; if (String.IsNullOrEmpty(idModel.Id)) { result.AddSystemError(Resources.ValidationResource.IDIsRequired, entity.GetType().Name); } else { if (idModel.Id == Guid.Empty.ToId()) { result.AddSystemError(Resources.ValidationResource.IDMustNotBeEmptyGuid, entity.GetType().Name); } if (idModel.Id == "0") { result.AddSystemError(Resources.ValidationResource.IDMustNotBeZero, entity.GetType().Name); } } } }
public static bool TryValidateValue(IValidateable o, string propName, object value, ICollection <ValidationResult> errors) // throws ArgumentNullException and System.ComponentModel.DataAnnotations.ValidationException!! { bool isDefined = Attribute.IsDefined(o.GetType().GetProperty(propName), typeof(RegularExpressionAttribute)); ValidationContext vc = new ValidationContext(o, null, null); var attrList = new List <ValidationAttribute>(); ValidationAttribute att = GetAttribute <RegularExpressionAttribute>(o, propName); if (att != null) { attrList.Add(att); } ; //if (( att = GetAttribute<RequiredAttribute>(o, propName)) != null) attrList.Add(att); if ((att = GetAttribute <StringLengthAttribute>(o, propName)) != null) { attrList.Add(att); } return(isDefined ? System.ComponentModel.DataAnnotations.Validator.TryValidateValue(value, vc, errors, attrList) : true); }
public static A GetAttribute <A>(IValidateable o, string prop) where A : Attribute { return(o.GetType().GetProperty(prop).GetCustomAttributes(typeof(A), false).Cast <A>().Single()); }
/// <summary> /// Validate an IValidateable object. /// </summary> /// <param name="entity">Object to validate</param> /// <param name="action">Action to execute: if not specified, use Any, this is normally used for custom validation routines</param> /// <param name="requirePopulatedEHValues">If this is set to true it will require that the entire object graphs, including traversing through EntityHeader<T>.Value will be required if the parameter is required.</param> /// <returns></returns> public static ValidationResult Validate(IValidateable entity, Actions action = Actions.Any, bool requirePopulatedEHValues = false) { var result = new ValidationResult(); if (entity == null) { if (SLWIOC.Contains(typeof(ILogger))) { var logger = SLWIOC.Get <ILogger>(); logger.AddException("Validator_Validate", new Exception("NULL Value Passed to Validate Method")); } result.AddSystemError("Null Value Provided for model on upload."); return(result); } ValidateAuditInfo(result, entity); ValidateId(result, entity); var properties = entity.GetType().GetTypeInfo().GetAllProperties(); foreach (var prop in properties) { var attr = prop.GetCustomAttributes(typeof(FormFieldAttribute), true).OfType <FormFieldAttribute>().FirstOrDefault(); if (attr != null) { ValidateProperty(attr, result, entity, prop, action); } } var methods = entity.GetType().GetTypeInfo().DeclaredMethods; foreach (var method in methods) { var attr = method.GetCustomAttributes(typeof(CustomValidatorAttribute), true).OfType <CustomValidatorAttribute>().FirstOrDefault(); if (attr != null) { CallCustomValidationRoutine(attr, result, entity, method, action); } } foreach (var prop in properties) { var attr = prop.GetCustomAttributes(typeof(FormFieldAttribute), true).OfType <FormFieldAttribute>().FirstOrDefault(); var propValue = prop.GetValue(entity); if (propValue != null) { if (propValue is IValidateable validateablePropValue) { var childResult = Validator.Validate(validateablePropValue, action); result.Concat(childResult); } if (propValue.GetType().GetTypeInfo().IsGenericType&& propValue.GetType().GetGenericTypeDefinition() == typeof(EntityHeader <>)) { var valueProperty = propValue.GetType().GetTypeInfo().GetDeclaredProperty("Value"); if (valueProperty.GetValue(propValue) is IValidateable validatableChild) { var childResult = Validator.Validate(validatableChild, action); result.Concat(childResult); } else { if (attr != null && attr.IsRequired && requirePopulatedEHValues) { AddRequiredFieldMissingMessage(result, attr, prop.Name); } } } if (prop.GetValue(entity) is System.Collections.IEnumerable listValues) { foreach (var listValue in listValues) { if (listValue is IValidateable validatableListValue) { var childResult = Validator.Validate(validatableListValue, action); result.Concat(childResult); } } } } } return(result); }
private static void ValidateString(ValidationResult result, PropertyInfo propertyInfo, FormFieldAttribute attr, String value, IValidateable entity) { var propertyLabel = GetLabel(attr); if (String.IsNullOrEmpty(propertyLabel)) { propertyLabel = propertyInfo.Name; } if (String.IsNullOrEmpty(value) && attr.IsRequired) { var validationMessage = String.Empty; if (attr.FieldType == FieldTypes.Hidden) { result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name), entity.GetType().Name); } else { if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null) { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource); result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null), entity.GetType().Name); } else if (!String.IsNullOrEmpty(attr.LabelDisplayResource)) { validationMessage = Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel); result.AddUserError(validationMessage, entity.GetType().Name); } else { result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name), entity.GetType().Name); } } } if (!String.IsNullOrEmpty(value)) { if (attr.FieldType == FieldTypes.Key) { var reEx = new Regex("^[a-z0-9]{3,30}$"); if (!reEx.Match(value).Success) { if (attr.ResourceType == null) { throw new Exception($"Validating String - Reg Ex Validation has a resource text, but no resource type for field [{attr.LabelDisplayResource}]"); } result.AddUserError(ValidationResource.Common_Key_Validation, entity.GetType().Name); } } if (!String.IsNullOrEmpty(attr.RegExValidation)) { var reEx = new Regex(attr.RegExValidation); if (!reEx.Match(value).Success) { if (attr.ResourceType == null) { throw new Exception($"Validating String - Reg Ex Validation was invalid, but no resource type for field [{attr.LabelDisplayResource}]"); } if (String.IsNullOrEmpty(attr.RegExValidationMessageResource)) { throw new Exception($"Validating String - Reg Ex Validation was invalid, [RegExValidationMessageResource] was null or empty and could not lookup error message for invalid field [{attr.LabelDisplayResource}]."); } else { var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RegExValidationMessageResource); if (validationProperty == null) { throw new Exception($"Validating String - Reg Ex Validation was invalid, but could not find validation message resource for field [{attr.LabelDisplayResource}]"); } else { result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null), entity.GetType().Name); } } } } if (attr.MinLength.HasValue && attr.MaxLength.HasValue) { if (value.Length < attr.MinLength || value.Length > attr.MaxLength) { result.AddUserError(Resources.ValidationResource.ValueLength_Between.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()).Replace("[MAX]", attr.MaxLength.ToString()), entity.GetType().Name); } } else if (attr.MaxLength.HasValue) { if (value.Length > attr.MaxLength) { result.AddUserError(Resources.ValidationResource.ValueLength_TooLong.Replace("[PROPERTY]", propertyLabel).Replace("[MAX]", attr.MaxLength.ToString()), entity.GetType().Name); } } else if (attr.MinLength.HasValue) { if (value.Length < attr.MinLength) { result.AddUserError(Resources.ValidationResource.ValueLength_TooShort.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()), entity.GetType().Name); } } } }
private static void ValidateAuditInfo(ValidationResult result, IValidateable entity) { if (entity is IAuditableEntity) { var auditableModel = entity as IAuditableEntity; if (String.IsNullOrEmpty(auditableModel.CreationDate)) { result.AddSystemError(Resources.ValidationResource.CreationDateRequired, entity.GetType().Name); } else if (!auditableModel.CreationDate.SuccessfulJSONDate()) { if (DateTime.TryParse(auditableModel.CreationDate, CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dateTime)) { auditableModel.CreationDate = dateTime.ToJSONString(); } else { result.AddSystemError(Resources.ValidationResource.CreationDateInvalidFormat + " " + auditableModel.CreationDate, entity.GetType().Name); } } if (String.IsNullOrEmpty(auditableModel.LastUpdatedDate)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedDateRequired, entity.GetType().Name); } else if (!auditableModel.LastUpdatedDate.SuccessfulJSONDate()) { if (DateTime.TryParse(auditableModel.LastUpdatedDate, CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dateTime)) { auditableModel.LastUpdatedDate = dateTime.ToJSONString(); } else { result.AddSystemError(Resources.ValidationResource.LastUpdateDateInvalidFormat + " " + auditableModel.LastUpdatedDate, entity.GetType().Name); } } if (auditableModel.LastUpdatedBy == null) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByNotNull, entity.GetType().Name); } else { if (String.IsNullOrEmpty(auditableModel.LastUpdatedBy.Id)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByIdNotNullOrEmpty, entity.GetType().Name); } else if (!auditableModel.LastUpdatedBy.Id.SuccessfulId()) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByIdInvalidFormat, entity.GetType().Name); } if (String.IsNullOrEmpty(auditableModel.LastUpdatedBy.Text)) { result.AddSystemError(Resources.ValidationResource.LastUpdatedByTextNotNullOrEmpty, entity.GetType().Name); } } if (auditableModel.CreatedBy == null) { result.AddSystemError(Resources.ValidationResource.CreatedByNotNull, entity.GetType().Name); } else { if (String.IsNullOrEmpty(auditableModel.CreatedBy.Id)) { result.AddSystemError(Resources.ValidationResource.CreatedByIdNotNullOrEmpty, entity.GetType().Name); } else if (!auditableModel.CreatedBy.Id.SuccessfulId()) { result.AddSystemError(Resources.ValidationResource.CreatedByIdInvalidFormat, entity.GetType().Name); } if (String.IsNullOrEmpty(auditableModel.CreatedBy.Text)) { result.AddSystemError(Resources.ValidationResource.CreatedByTextNotNullOrEmpty, entity.GetType().Name); } } } }