Custom validator class

In Ruby On Rails, most of the model validations are covered with ActiveModel::Validations.
However, there is a need for custom validation.
Then it makes sense to move the validation logic into a separate validation class.

Validation use case

A simplified User model as a starting example:

railsgmodelUseremail:stringpassword:string

The password should be present and have a minimum length of 6 characters. In addition, the password complexity has to be validated. Here it should be either a combination of uppercase/ lowercase, uppercase/ number or lowercase/ number:

The Validation logic has to be implemented in validate_each. The passed parameters are the object (user), the attribute (password), and the value (the password itself). There is also the possibility to access options. These are the known default options (message, allow_nil, allow_blank, on, if, unless, strict). The with option is for additional parameters. It is passed to the custom validator, as known from standard validators, like the LengthValidator.

Using custom validator

The model readability benefits from moving the validation logic into a custom validator:

The ComplexityValidator is defined with a complexity of 2.
Furthermore the validator can be combined with other validators (in this case, the LengthValidator).
If a higher password complexity is required for other user roles, like administrators, this is pretty easy to implement. For example, in a Form object that is responsible for creating administrators: