// ******************************************************************* /// <summary> /// This method validates the current object and throws an exception /// with the contents of any failing validations. /// </summary> /// <exception cref="ArgumentException">This exception is thrown whenever /// the argument is missing, or null.</exception> /// <exception cref="ValidationException">This exception is thrown if /// any of the validation checks fail.</exception> public static void ThrowIfInvalid( this IValidatableObject validatableObject ) { // Validate the parameters before attempting to use them. Guard.Instance().ThrowIfNull(validatableObject, nameof(validatableObject)); // Validate ourselves. var results = validatableObject.Validate( new ValidationContext(validatableObject) ); // Did anything fail? if (results.Any()) { // Format the invalid member names. var memberNames = string.Join( ",", results.Select(x => string.Join(",", x.MemberNames)) ); // Format the error message. var errorMessages = string.Join( ",", results.Select(x => x.ErrorMessage) ); // Throw the exception. throw new ValidationException( message: string.Format( Resources.VerifiableObject_Invalid, validatableObject.GetType().Name, errorMessages, memberNames ) ); } }
public virtual IEnumerable <DbValidationError> Validate( EntityValidationContext entityValidationContext, InternalMemberEntry property) { if (property != null && property.CurrentValue == null) { return(Enumerable.Empty <DbValidationError>()); } ValidationContext validationContext = entityValidationContext.ExternalValidationContext; validationContext.SetDisplayName(property, this._displayAttribute); IValidatableObject validatableObject = property == null ? (IValidatableObject)entityValidationContext.InternalEntity.Entity : (IValidatableObject)property.CurrentValue; IEnumerable <ValidationResult> validationResults; try { validationResults = validatableObject.Validate(validationContext); } catch (Exception ex) { throw new DbUnexpectedValidationException(Strings.DbUnexpectedValidationException_IValidatableObject((object)validationContext.DisplayName, (object)ObjectContextTypeCache.GetObjectType(validatableObject.GetType())), ex); } return(DbHelpers.SplitValidationResults(validationContext.MemberName, validationResults ?? Enumerable.Empty <ValidationResult>())); }
public static ValidationResult Is <TValue>(this IValidatableObject validatable, Func <TValue, bool> predicate, TValue value, string name) { return(predicate != null && predicate(value) ? new ValidationResult(validatable.GetType().Name + "." + name, new[] { name }) : null); }