Skip to content
Arxisos edited this page Dec 29, 2011 · 31 revisions

Validation

(available in the next release of ServiceStack)

ServiceStack includes a very clean way to validate request DTOs. Even contextual validation for each HTTP method (GET, POST, ...) is supported.

FluentValidation for request dtos

This request dto should be validated:

[RestService("/users")]
public class User
{
    public string Name { get; set; }
    public string Company { get; set; }
    public int Age { get; set; }
    public int Count { get; set; }
    public string Address { get; set; }
}

The validation rules for this request dto are made with FluentValidation (http://fluentvalidation.codeplex.com/documentation). ServiceStack makes heavy use of rule sets (http://fluentvalidation.codeplex.com/wikipage?title=CreatingAValidator&referringTitle=Documentation&ANCHOR#RuleSets) to provide different validation rules for each HTTP method (GET, POST, PUT...).

Tip: First read the documentation about FluentValidation before you continue reading

public interface IAddressValidator
{
    bool ValidAddress(string address);
}

public class AddressValidator : IAddressValidator
{
    public bool ValidAddress(string address)
    {
	return address != null
	    && address.Length >= 20
	    && address.Length <= 250;
    }
}

public class UserValidator : UserValidator<Validated>
{
    public IAddressValidator AddressValidator { get; set; }
    
    public UserValidator()
    {
        //Validation rules for all requests
        RuleFor(r => r.Name).NotEmpty();
        RuleFor(r => r.Age).GreaterThan(0);
        RuleFor(x => x.Address).Must(x => AddressValidator.ValidAddress(x));

        //Validation rules for GET request
        RuleSet(ApplyTo.Get, () =>
            {
                RuleFor(r => r.Count).GreaterThan(10);
            });

        //Validation rules for POST and PUT request
        RuleSet(ApplyTo.Post | ApplyTo.Put, () =>
            {
                RuleFor(r => r.Company).NotEmpty();
            });
    }
}

Info: ServiceStack adds another extension method named RuleSet which can handle ApplyTo enum flags. This method doesn't exist in the core FluentValidation framework.

Warning: If a validator for a request dto is created, all rules which aren't in any rule set are executed + the rules in the matching rule set. Normally FluentValidation only executes the matching rule set and ignores all other rules (whether they're in a rule set or not) and the rules which don't belong to any rule set are normally only executed, if no rule set-name was given to the validate method of the validator.

Like services registered in the IoC container, validators are also auto-wired, so if there's a public property which can be resolved by the IoC container, the IoC container will inject it. In this case, the IoC container will resolve the property AddressValidator, if an object of the type IAdressValidator was registered.

All validators have to be registered in the IoC container. So add this code to the app host:

//Enable the validation feature
ValidationFeature.Init(this);

//This method scans the assembly for validators
container.RegisterValidators(typeof(UserValidator).Assembly);

//Add the IAdressValidator which will be injected into the UserValidator
container.Register<IAddressValidator>(new AddressValidator());

Now the service etc can be created and the validation rules are checked every time a request comes in.

If you try now for example to send this request:

POST localhost:50386/validated
{
    "Name": "Max"
} 

You'll get this JSON response:

{
    "ErrorCode": "GreaterThan",
    "Message": "'Age' must be greater than '0'.",
    "Errors": [
        {
            "ErrorCode": "GreaterThan",
            "FieldName": "Age",
            "Message": "'Age' must be greater than '0'."
        },
        {
            "ErrorCode": "NotEmpty",
            "FieldName": "Company",
            "Message": "'Company' should not be empty."
        }
    ]
}

As you can see, the ErrorCode and the FieldName provide an easy way to handle the validation error at the client side. If you want, you can also configure a custom ErrorCode for a validation rule:

RuleFor(x => x.Name).NotEmpty().WithErrorCode("ShouldNotBeEmpty"); 

If the rule fails, the JSON response will look like that:

...
{
    "ErrorCode": "ShouldNotBeEmpty",
    "FieldName": "Name",
    "Message": "'Name' should not be empty."
}
...

Use FluentValidation everywhere!

Of course FluentValidation can be used for any other classes (not only request DTOs), too:

public class TestClass
{
    public string Text { get; set; }
    public int Length { get; set; }
}

Now the validator:

public class TestClassValidator : AbstractValidator<TestClass>
{
    public TestClassValidator()
    {
        RuleFor(x => x.Text).NotEmpty();
        RuleFor(x => x.Length).GreaterThan(0);
    }
}

Info: If FluentValidation isn't used for request DTOs, it behaves the same as documented in the Fluent Validation documentation.

Inside some service code you can validate an instance of this class:

public class SomeService : RestServiceBase<Validated>
{
    //You should have registered your validator in the IoC container to inject the validator into this property
    public IValidator<TestClass> Validator { get; set; }

    public override object OnGet(Validated request)
    {
        TestClass instance = new TestClass();

        ValidationResult result = this.Validator.Validate(instance);

        if (!result.IsValid)
        {
            //The result will be serialized into a ValidationErrorException and throw this one
            //The errors will be serialized in a clean, human-readable way (as the above JSON example)
            throw result.ToException();
        }

    }
}


  1. Getting Started
    1. Create your first webservice
    2. Your first webservice explained
    3. ServiceStack's new API Design
    4. Designing a REST-ful service with ServiceStack
    5. Example Projects Overview
  2. Reference
    1. Order of Operations
    2. The IoC container
    3. Metadata page
    4. Rest, SOAP & default endpoints
    5. SOAP support
    6. Routing
    7. Service return types
    8. Customize HTTP Responses
    9. Plugins
    10. Validation
    11. Error Handling
    12. Security
    13. Debugging
  3. Clients
    1. Overview
    2. C# client
    3. Silverlight client
    4. JavaScript client
    5. Dart Client
    6. MQ Clients
  4. Formats
    1. Overview
    2. JSON/JSV and XML
    3. ServiceStack's new HTML5 Report Format
    4. ServiceStack's new CSV Format
    5. MessagePack Format
    6. ProtoBuf Format
  5. View Engines 4. Razor & Markdown Razor
    1. Markdown Razor
  6. Hosts
    1. IIS
    2. Self-hosting
    3. Messaging
    4. Mono
  7. Security
    1. Authentication/authorization
    2. Sessions
    3. Restricting Services
  8. Advanced
    1. Configuration options
    2. Access HTTP specific features in services
    3. Logging
    4. Serialization/deserialization
    5. Request/response filters
    6. Filter attributes
    7. Concurrency Model
    8. Built-in caching options
    9. Built-in profiling
    10. Form Hijacking Prevention
    11. Auto-Mapping
    12. HTTP Utils
    13. Virtual File System
    14. Config API
    15. Physical Project Structure
    16. Modularizing Services
    17. MVC Integration
  9. Plugins 3. Request logger 4. Swagger API
  10. Tests
    1. Testing
    2. HowTo write unit/integration tests
  11. Other Languages
    1. FSharp
    2. VB.NET
  12. Use Cases
    1. Single Page Apps
    2. Azure
    3. Logging
    4. Bundling and Minification
    5. NHibernate
  13. Performance
    1. Real world performance
  14. How To
    1. Sending stream to ServiceStack
    2. Setting UserAgent in ServiceStack JsonServiceClient
    3. ServiceStack adding to allowed file extensions
    4. Default web service page how to
  15. Future
    1. Roadmap

Clone this wiki locally