Don't settle for incomplete data!
Get data from the user in the form you want!
Get...VALIDATION!
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...
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."
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
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
Check out the Rails Guide for other handy validation methods!
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>
...Create a method in your Model that allows you to display the User's phone number in this style:
(###) ### - ####