0
0
Ruby on Railsframework~30 mins

Format validation in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
Format Validation in Rails Models
📖 Scenario: You are building a simple Rails application to store user profiles. Each user must have a username that only contains letters and numbers, and an email address that follows a standard email format.
🎯 Goal: Create a Rails model called User with attributes username and email. Add format validations to ensure the username contains only letters and numbers, and the email is in a valid email format.
📋 What You'll Learn
Create a User model with username and email attributes
Add a format validation for username to allow only letters and numbers
Add a format validation for email to ensure it matches a standard email pattern
Use Rails built-in validation helpers and regular expressions
💡 Why This Matters
🌍 Real World
Format validations are essential in web apps to ensure user input meets expected patterns, preventing errors and improving data quality.
💼 Career
Understanding how to apply format validations in Rails models is a common task for backend developers working on user authentication and data integrity.
Progress0 / 4 steps
1
Create the User model with username and email attributes
Create a Rails model called User with string attributes username and email.
Ruby on Rails
Need a hint?

Use rails generate model User username:string email:string to create the model and attributes.

2
Add a format validation for username
Add a format validation to the User model that ensures username contains only letters and numbers using the regular expression /\A[a-zA-Z0-9]+\z/.
Ruby on Rails
Need a hint?

Use validates :username, format: { with: /\A[a-zA-Z0-9]+\z/ } to restrict characters.

3
Add a format validation for email
Add a format validation to the User model that ensures email matches the regular expression /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/ to validate standard email format.
Ruby on Rails
Need a hint?

Use validates :email, format: { with: /\A[^@\s]+@[^@\s]+\.[^@\s]+\z/ } to check email format.

4
Complete the User model with both validations
Ensure the User model includes both format validations for username and email as specified.
Ruby on Rails
Need a hint?

Check that both validations are present in the model.