Monday, 12 October 2015

Add FluentValidation Rules to Swagger Schema

The following code uses the FluentValidation IValidator profiles to add extra data to the swagger schema such as required and min/max lengths.

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
        }
    }

3 comments:

  1. Hi John.
    I'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

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. There is new project that covers wide aspects of intergration Swagger and FluentValidation:

    https://github.com/micro-elements/MicroElements.Swashbuckle.FluentValidation

    ReplyDelete