Validation on Rails
Input, As You Like It
don't accept bad input
Don't settle for incomplete data!
Get data from the user in the form you want!
Get...VALIDATION!
You Gotta Gimme something...
There's good data, bad data, and then there's just no data at all.
Don't let the user leave you high and dry!
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
end
We'll start with "presence" validations in the Model...
That's the way...
Yaml-ike it!
We have the power to control what our error messages say!
Visit: config/locales/en.yml
en:
hello: "Hello world"
activerecord:
attributes:
user:
first_name: "A first name"
last_name: "A last name"
errors:
models:
user:
attributes:
first_name:
blank: " must be entered! MUST!"
last_name:
blank: " is required. Because I say so."
we're already got one of those
The "uniqueness" validation, among other uses, keeps a user from registering on your app multiple times.
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, uniqueness: true
end
no dashes, no dots
A phone number can be a tricky bit of data to take from a User. People write them all sorts of ways.
Try limiting the number of characters accepted, and using leading error messages.
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, uniqueness: true
validates :phone_number, length: { minimum: 10, maximum: 10,
too_short: "is 10 digits long. Maybe you forgot the area code?",
too_long: "is 10 digits long. Don't put in any dashes or (), please." }
end
The Wide World of Validations...
Check out the Rails Guide for other handy validation methods!
You've got the data, now make it your own!
We can create methods in the Model to customize the look of our data.
#in the User model:
def full_name
"#{first_name} #{last_name}"
end
# in the User show page:
<p>
<strong>Full name:</strong>
<%= @user.full_name %>
</p>
i bet you can't...
...Create a method in your Model that allows you to display the User's phone number in this style:
(###) ### - ####
Rails Validations
By argroch
Rails Validations
Setting validations on user input.
- 1,121