I was recently reading an article by Martin Fowler where he was using JSON to describe validation rules for your model.
I created an small example to demonstrate that (it requires Java 8). On it, our model is composed of a single class, called
City. It contains the city’s name, plus the population. In order to be valid it must follow these simple rules:
- None of the fields can be null;
- The name cannot contain numbers;
- The population must be a natural number (
n >= 0).
Here you can see the model and the interface of our
Validator. It returns an instance of
Validation, that can either be a
Invalid object, representing the validation result.
With that we can create an implementation of the
script), but it could as well be coming from a file.
Finally, we can get a few examples running and check the results:
Map. Since our backend web API received JSON objects, we could instead pass the JSON object directly to the
Validator, avoiding translating JSON to Scala, and from Scala to JS, in order to validate it.
Having your model as JSON is also interesting because the approach allows the use of JSON Schema. Assuming your have your model object converted to JSON, you can use json-schema-validator to do the following:
Furthermore, another option is to use Scala.js, which might provide a cleaner solution.
- Services Version Lock with Docker and Jenkins
- Circuit Breakers and retries in Scala with autobreaker
- Efficient Timer using a Circular Buffer
- Proxy annotated objects with Guice
- Integration testing for nginx Routes
- Type Equality Checking at Compile Time in Scala
- O(1) LFU Cache in Scala
- Problems with Branches per Environment
- Trunk Based Development with Multiple Services
- Tips for your Distributed Project Inception or Meeting