A sign in form simply populates the sessions hash, and so doesn't have a model. As such, I don't know where to put validations for the sign in form. How should I validate presence of the username and password? Should I just do it with javascript on the clientside? I suppost that makes sense, how could I iterate through the errors hash if it were to fail validations?
Really simple, you can realize it using ActiveModel
. Just create a class as below and add some validations
class Session
include ActiveModel::Validations
extend ActiveModel::Naming
attr_accessor :username, :password
validates_presence_of :username, :password
def initialize(attrs = {})
attrs.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
s = Session.new(username: 'Abc')
=> #<Session:0x000000058a3270 @username="Abc">
s.valid?
s.errors
=> #<ActiveModel::Errors:0x000000058ad900 ... @messages={:password=>["can't be blank"]}>
And your form should automatically show error messages if exists.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments