Learn Dry Validation in Ruby On Rails – P1

Tram Ho

▪️ First, I will introduce about Dry Validation
  • dry-validation is the validation data library provided by DSL, it works with any input data, whether it is a hash, an array or an object containing deep nested data.
  • Validations are expressed through Contract object . A Contract will define a schema with basic data check types and any applicable rules . Contract rules are only applied once the values ​​they are based on are passed through the basic schema data check types.
  • Using it will be much faster than using ActiveRecord/ActiveModel::Validations , strong-parameters .
  • To be able to use it in your project we need to install it first by adding the gem 'dry-validation' the gem 'dry-validation' of the ROR project.
▪️ Let’s begin to learn the basics of this library:
1. Type Validate Basic
  • Some types of check validate commonly used in dry I can mention:

2. Schemas
  • It can be said that Schemas is an important part of dry-validation , it will process the data before it is validated by the rules (and what rules are below I will learn more) and Schemas can provide Error message in the most detailed way
  • rules here can understand that I will validate the data in a more specific way (the data needs to be logically validated) that the gem validate types do not support.

? Define a basic schema

  • To define a schema we will use the schema method:

  • Above we have created a Contact with the required use which means the input must have email , the age and value of the email must be string and the value of age must be integer
  • Now, we will try to apply the Contract we just created:


? Defining a Schema with Params required

  • To define a schema for validating HTTP parameters , we will use the params method:

  • The main difference between params and schema is simply that params will implement params enforced rules before applying rules . In the rules section we will learn more clearly.

? Define a schema with json required

  • We can use json to define an appropriate schema for validating JSON data:


? Reuse schema from other schema

  • We can use a schema is or multiple schema by passing it into schema we define. For example:


? Custom Types for Schema

  • When we define the schema using param or json , we can handle the value of the input data the way we want, for example:


Thank you for reading my article

Reference: Dry Validation

Share the news now

Source : Viblo