For Developers

The time you code and you realized that your brain want to spark to fire, kindly follow these steps.. “For Developers” is published by Yusuf Abubakar Mai.

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Custom ActiveRecord Validator

Active Record validation is one of the impartial magic in Rails. These validations are used to ensure only valid data are forwarded to the database. Validations are usually placed on the model that makes it easily testable and maintainable. Here is an example of validation that validates the field as numerical.

ActiveRecord validators are really easy and simple to understand. Even though Rails provides the utmost validations, sometimes we need to have our own validator based on our business logic and the application-specific validations. Let’s take an example of an application where the business is specific to Nepal and the user needs a Nepalese phone number. The business requirement is that the phone number must be valid only if it matches the criteria for a Nepalese phone number. This requirement can be fulfilled by adding the custom validation in the model defining a method to validate the input as follows:

The above method adds an error and prevents saving data in the database if the number does not satisfy the regex for the Nepalese phone number. This is perfect but sometimes application needs the same validations in multiple places. For eg, the phone number validations might be required in the client number, a contact person number, and so on. We can definitely keep the method in the module and include it in each model as required if the field name is the same or with some tweaks for the different field names. Here comes the role of Active Record Custom Validator.

We can create a custom validator file inside the validators folder as follows:

This validator can be easily integrated into any field that requires to be the Nepalese phone number.

This approach really helps to keep the code clean and maintainable in the large app where we need to validate different fields in different ways based on the business need. Happy Coding!!

Add a comment

Related posts:

Accessing Undocumented Azure DevOps APIs

Azure DevOps has some pretty useful APIs, but it doesn’t have everything I want. For quite some time I found it frustrating that some of the stuff I wanted to do could only be done via portal clicky…

The Empress Needs New Clothes

I feel so irritated like I don’t belong in my skin. Can’t put my finger on it, I don’t like this feeling of being beaten and bruised, by people’s unwarranted hostility. Called cocksucker and fucking…

Prepare for the Rise of Eurasia

What have I been up to lately? Thanks for asking; I’ve been reading, mostly non-fiction books and news articles, and formulating informal theories about the evolution of the global power structure…