Pariksha : Scala validation library

Image for post
Image for post

Recently i started working on a library that does validation on scala types.

The original aim was to write a library that was could be used for data validation on incoming api requests in a web application . Then i saw some other scala validation libraries like Accord and octopus and i thought to extend the ideas expressed there. The source code for Pariksha (which means test in Hindi) can be found at https://github.com/ayushworks/pariksha

The protagonist of our story is the Validator[T] trait which validates instances of T by using a list of Validation[T].

Consider a simple case class

We can define a list of Validation for this type

And then we can validate any instance of Employee type. All we need is Validator[Employee] implicitly in scope

validate returns a ValidationResult which can have two possible values

  • Valid
  • Invalid

Everybody knows Jenna Fischer from the office!

And for an invalid employee

Nested Validations

When we have a type that contains another type, and we already have a Validator for the nested type, we can use the existing validator and delegate to that.

We could define validations for Manager to be used in multiple places

Then we we can define validations for the Office class and use the previous validator automatically for the manager field, assuming it is available as an implicit in the current scope.

Note, how we use the validate method on the contained type.

Fail Fast Validations

Sometimes it is desirable to not run all validations exhaustively but rather stop on first failed validation.

We can use the validateFailFast method on a type T . The requirements remain the same with a presence of Validator[T] needed.

The second check is not even called in this case as the first one had failed. This is useful when the validations are resource/time consuming and we would like to stop at the first sign of problems.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store