usage
c.SchemaFilter<AddFluentValidationRules>();
Code
public class AddFluentValidationRules : ISchemaFilter { public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type) { var validator = GetValidator(type); if (validator == null) { return; } schema.required = new List<string>(); var validatorDescriptor = validator.CreateDescriptor(); foreach (var key in schema.properties.Keys) { foreach (var propertyValidator in validatorDescriptor.GetValidatorsForMember(key)) { if (propertyValidator is NotEmptyValidator) { schema.required.Add(key); } if (propertyValidator is LengthValidator) { var lengthValidator = (LengthValidator) propertyValidator; if (lengthValidator.Max > 0) { schema.properties[key].maxLength = lengthValidator.Max; } schema.properties[key].minLength = lengthValidator.Min; } if (propertyValidator is RegularExpressionValidator) { var regexExpressionValidator = (RegularExpressionValidator) propertyValidator; schema.properties[key].pattern = regexExpressionValidator.Expression; } } } } private IValidator GetValidator(Type t) { // use IoC or FluentValidatorFactory to get AbstractValidator<T> instance } }
Hi John.
ReplyDeleteI've ran into an issue with Nested Objects and I posted it on Stackoverflow.
http://stackoverflow.com/questions/38768732/swagger-does-not-recognise-fluent-validation-of-nested-objects
Best regards,
Gustavo Michel
This comment has been removed by the author.
ReplyDeleteThere is new project that covers wide aspects of intergration Swagger and FluentValidation:
ReplyDeletehttps://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation