I refer to the Rails guide and so on. https://railsguides.jp/active_record_validations.html
【Thing you want to do】 ・ Leave your name and email address blank so that you cannot register. ・ Character limit for name and email address
The point is ① "presence: true" → Prohibit registration in the blank ② "length: {maximum:}" → Prohibit length longer than the number set after ":"
You will be working on the app / models / user.rb file. I created the following code.
class User < ApplicationRecord
validates :name, presence: true, length: { maximum: 20 }
validates :email, presence: true, length: { maximum: 300 },
end
Check the Rails console to see if it works. First of all, when I try to register in the blank. .. ..
> User.create(name: "", email: "")
(0.3ms) BEGIN
(0.4ms) ROLLBACK
=> #<User id: nil, name: "", email: "", created_at: nil, updated_at: nil>
It is not registered by ROLLBACK.
And if you try to register a long name or email address, you can see that this is also ROLLBACK (the part marked with ... in the email column is too long to be displayed in the article).
> user = User.create(name: "a"*25 , email: "b"*350 + "@test.com")
> (0.3ms) BEGIN
> (0.4ms) ROLLBACK
=> #<User:
id: nil,
name: "aaaaaaaaaaaaaaaaaaaaaaaaa",
email:"[email protected]",
created_at: nil,
updated_at: nil>
When displaying the reason for the error. .. ..
> user.errors.messages
> {:name=>["is too long (maximum is 20 characters)"],
:email=>["is too long (maximum is 300 characters)"]}
I have confirmed that "length: {maximum:}" is working properly.
By the way, the part that is maximum seems to be applicable in various ways. (From the Rails guide below)
class Person < ApplicationRecord
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
validates :registration_number, length: { is: 6 }
end
:minimum:The attribute cannot take a value smaller than this value.
:maximum:The attribute cannot take a value greater than this value.
:in or:within:The length of the attribute must be within the given interval. The value of this option must be a range.
:is:The length of the attribute must be equal to the given value.
Recommended Posts