/// <summary> /// Validates the specified property using data annotation attributes. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns> /// <see langword="true"/> if the property is valid; otherwise, <see langword="false"/> if /// it has errors. /// </returns> public bool ValidateProperty(string propertyName) { if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException(nameof(propertyName)); } var propertyInfo = GetType().GetRuntimeProperty(propertyName); if (propertyInfo == null) { throw new ArgumentException("Invalid property name", propertyName); } if (!propertyInfo.GetCustomAttributes(typeof(ValidationAttribute)).Any()) { return(true); } var errors = new List <string>(); bool isValid = TryValidateProperty(propertyInfo, errors); ErrorsContainer.SetErrors(propertyInfo.Name, errors); return(isValid); }
/// <summary> /// Validates all properties using data annotation attributes. /// </summary> /// <returns> /// <see langword="true"/> if all properties are valid; otherwise, <see langword="false"/> /// if it has errors. /// </returns> /// <remarks> /// This method does not check for entity-level errors. It only validates properties using /// data annotation attributes. /// </remarks> public bool ValidateProperties() { // Get all the properties decorated with the ValidationAttribute. var propertiesToValidate = GetType().GetRuntimeProperties() .Where(c => c.GetCustomAttributes(typeof(ValidationAttribute)).Any()); bool isValid = true; var errors = new List <string>(); foreach (var propertyInfo in propertiesToValidate) { errors.Clear(); isValid &= TryValidateProperty(propertyInfo, errors); ErrorsContainer.SetErrors(propertyInfo.Name, errors); } return(isValid); }