internal ValidationResult?ValidateModel(IArgumentModel model) { Type modelType = model.GetType(); Type?declaredValidatorType = modelType.GetCustomAttribute <ValidatorAttribute>()?.ValidatorType; if (declaredValidatorType is { })
private static IEnumerable <string> GetArgumentModelErrors(IArgumentModel model, IReadOnlyCollection <IArgument> arguments) { var validationContext = new ValidationContext(model); var results = new List <ValidationResult>(); if (Validator.TryValidateObject(model, validationContext, results, validateAllProperties: true)) { return(Enumerable.Empty <string>()); } IArgument?GetArgument(string propertyName) { return(arguments.FirstOrDefault(a => { var info = a.Services.GetOrDefault <PropertyInfo>(); return info != null && info.DeclaringType.IsInstanceOfType(model) && propertyName.Equals(info.Name); })); } string SanitizedErrorMessage(ValidationResult validationResult) { var errorMessage = validationResult.ErrorMessage; foreach (var memberName in validationResult.MemberNames) { var argument = GetArgument(memberName); if (argument is { }) { errorMessage = errorMessage.RemoveFieldTerminology(memberName, argument); } }
internal ValidationResult ValidateModel(IArgumentModel model) { Type modelType = model.GetType(); Type declaredValidatorType = modelType.GetCustomAttribute <ValidatorAttribute>()?.ValidatorType; if (declaredValidatorType != null) { object validator; try { if (_dependencyResolver == null || !_dependencyResolver.TryResolve(declaredValidatorType, out validator)) { validator = Activator.CreateInstance(declaredValidatorType); } } catch (Exception e) { throw new InvalidValidatorException($"Could not create instance of {declaredValidatorType.Name}. Please ensure it's injected via IoC or has a default constructor.\n" + "This exception could also occur if default constructor threw an exception", e); } return(((IValidator)validator).Validate(model)); } return(null); }
private void Validate(IArgumentModel model) { ValidationContext context = new ValidationContext(model); Validator.TryValidateObject(model, context, Errors, true); if (model.GetType().Name == "RegistrateAdministrator") { RegistrateAdministrator modelReg = model as RegistrateAdministrator; if (Users.First(x => x.Email == modelReg.Email) != null) { Errors.Add(new ValidationResult("This email is already in use")); } if (Credentials.First(x => x.Login == modelReg.Login) != null) { Errors.Add(new ValidationResult("This login is already in use")); } } }