[Ruby] Implementation of validation using regular expressions

1 minute read


This time, I will summarize how to implement validation using regular expressions.

First, I’ll briefly discuss validation and regular expressions.


It validates invalid data by validating it when saving the data. You can not register empty data, specify the characters that must be included in the character string, limit the number of characters, … There are various validations.

As a typical example, let’s validate it so that it is not empty when entering nickname.


- --abridgement---
validates :nickname, presence: true
- --abridgement---

I will validate each input item like this.

Regular expression

Regular expression is a syntax that combines symbols and character strings, and you can extract the specified character string pattern from the sentence to be searched.

If you use it often, \A… matches the beginning of a string \z… matches the end of a string There are some other things that look like.

There will be many if you search, so it seems that you do not need to remember.

Validation using regular expressions

What I would like to summarize this time is validation using regular expressions.

Specifically, we will implement the validation that the data to be entered in the password is alphanumeric characters.

The point is that you assign a regular expression to a variable and incorporate it into validation.


  validates :password, presence: true
  validates :password, length: {minimum: 6}
  VALID_PASSWORD_REGIX = /\A[a-z0-9]+\z/i
  validates :password, format: {with: VALID_PASSWORD_REGIX}

From top to bottom ・Password is required ・Password must be 6 characters or more ・Password must be alphanumeric Has been validated.

Tags: ,