0
0
Ruby on Railsframework~5 mins

Format validation in Ruby on Rails

Choose your learning style9 modes available
Introduction

Format validation helps check if data matches a specific pattern before saving it. It keeps your data clean and correct.

When you want to ensure an email address looks valid before saving it.
When you need to check that a phone number has the right digits and format.
When you want to confirm a postal code follows a certain pattern.
When you want to validate a username only contains allowed characters.
When you want to make sure a date string matches a specific format.
Syntax
Ruby on Rails
validates :attribute_name, format: { with: /pattern/, message: "error message" }
Use Ruby regular expressions (like /pattern/) to define the format.
The message option lets you customize the error shown if validation fails.
Examples
This checks that the email has an '@' and no spaces.
Ruby on Rails
validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email" }
This ensures the phone number is exactly 10 digits.
Ruby on Rails
validates :phone, format: { with: /\A\d{10}\z/, message: "must be 10 digits" }
This allows only letters, numbers, and underscores in usernames.
Ruby on Rails
validates :username, format: { with: /\A[a-zA-Z0-9_]+\z/, message: "only letters, numbers, and underscores allowed" }
Sample Program

This example creates a User model with email format validation. It tests one valid and one invalid email.

Ruby on Rails
class User < ApplicationRecord
  validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email" }
end

user1 = User.new(email: "test@example.com")
user2 = User.new(email: "invalid email")

puts user1.valid?  # true
puts user1.errors.full_messages.join(", ")
puts user2.valid?  # false
puts user2.errors.full_messages.join(", ")
OutputSuccess
Important Notes

Regular expressions are powerful but can be tricky; test them carefully.

Format validation only checks the pattern, not if the data actually exists (like a real email).

You can combine format validation with other validations for stronger checks.

Summary

Format validation checks if data matches a pattern using regular expressions.

It helps keep data clean by preventing wrong formats from saving.

Customize error messages to guide users on fixing input mistakes.