This time, I will summarize how to implement validation using regular expressions.
First, let's take a quick look at validation and regular expressions.
By validating when saving the data, it will play invalid data. You can't register empty data, specify characters that must be included in the character string, limit the number of characters, etc. There are various validations.
As a typical example, let's validate it so that it will not be empty when entering the nickname.
models/user.rb
---abridgement---
validates :nickname, presence: true
---abridgement---
Validate each input item like this.
A regular expression is a syntax that combines symbols and character strings, and can extract a 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 the string There are some others like this.
If you search, you will find a lot, so you don't need to remember it.
What I would like to summarize this time is validation using regular expressions.
Specifically, we will implement validation that the data entered in the password will be half-width alphanumeric characters.
The point is to assign a regular expression to a variable and incorporate it into validation.
models/user.rb
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 single-byte alphanumeric characters Validation is organized.
Recommended Posts