/// <summary> /// Creates an instance of the RequestValidator using the .net Validation framework as part of the DataAnnotations. /// The collection naming strategy can be overridden by creating a resolvable instance of <code>ICollectionPropertyNamingStrategy</code> /// in the serviceProvider /// </summary> /// <param name="serviceProvider"></param> public DataAnnotationsRequestValidator(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; var altStrategy = serviceProvider.GetService(typeof(ICollectionPropertyNamingStrategy)); if (altStrategy != null) { _collectionPropertyNamingStrategy = (ICollectionPropertyNamingStrategy)altStrategy; } }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (!(value is ICollection coll)) { return(ValidationResult.Success); } ICollectionPropertyNamingStrategy cpns = validationContext.GetService(typeof(ICollectionPropertyNamingStrategy)) as ICollectionPropertyNamingStrategy; string message = ""; int idx = 0; var members = new List <string>(); foreach (var c in coll) { RegularExpressionAttribute attr = new RegularExpressionAttribute(_pattern); var res = attr.GetValidationResult(c, validationContext); var invalid = !string.IsNullOrWhiteSpace(res?.ErrorMessage); if (invalid) { message = res.ErrorMessage; if (cpns != null) { members.Add(cpns.CreateName(validationContext.MemberName, idx, "")); } else { members.Add($"{validationContext.MemberName}[{idx}]"); } } idx++; } if (members.Any()) { return(new ValidationResult(message, members)); } return(ValidationResult.Success); }
public DataAnnotationsValidator(ICollectionPropertyNamingStrategy collectionValidationNaming) { _collectionValidationNaming = collectionValidationNaming ?? throw new ArgumentNullException(nameof(collectionValidationNaming)); }