class Kemal::Form
- Kemal::Form
- Reference
- Object
Overview
Kemal::Form
contains classes and macros that makes working with forms
in your Kemal application fun and easy.
require "kemal"
require "kemal-form"
class LoginForm < Kemal::Form
field username : Kemal::Form::TextField,
validators: [Kemal::FormValidator::Required.new]
field password : Kemal::Form::PasswordField,
validators: [
Kemal::FormValidator::Length.new(min: 6)
]
button login : Kemal::Form::SubmitButton,
text: "Login"
end
get "/login" do
form = LoginForm.new
render "src/views/login.ecr"
end
post "/login" do |env|
form = LoginForm.new env
if form.valid?
puts "You are now logged in"
env.redirect "/"
next
end
render "src/views/login.ecr"
end
Defined in:
kemal-form.crkemal-form/buttons.cr
kemal-form/errors.cr
kemal-form/field.cr
kemal-form/fields/common.cr
kemal-form/fields/select.cr
kemal-form/fields/textarea.cr
kemal-form/form.cr
kemal-form/label.cr
Constant Summary
-
VERSION =
"0.4.0"
Constructors
-
.new(ctx : Nil | HTTP::Server::Context = nil)
Initializes a new form.
Instance Method Summary
-
#add_error(message : String)
Adds error to the form.
-
#body : URI::Params
Returns the form body.
-
#buttons : Array(Button)
Returns the form's buttons.
-
#errors : Array(String)
Returns form errors.
-
#fields : Array(Field)
Returns the form's fields.
-
#valid? : Bool
Returns
true
if the form is valid,false
otherwise.
Constructor Detail
def self.new(ctx : Nil | HTTP::Server::Context = nil)
#
Initializes a new form.
class MyForm < Kemal::Form
end
get "/" do
form = MyForm.new
render "src/views/index.ecr"
end
post "/" do |env|
form = MyForm.new env
# ...
render "src/views/index.ecr"
Instance Method Detail
def add_error(message : String)
#
Adds error to the form.
post "/login" do |env|
form = LoginForm.new env
form.valid?
if wrong_password_entered
form.add_error "Invalid username or password"
...
end
...
end
...
end
def valid? : Bool
#
Returns true
if the form is valid, false
otherwise.
class MyForm < Kemal::Form
end
post "/" do |env|
form = MyForm.new env
if form.valid?
puts "form is valid"
env.redirect "/"
next
end
render "src/views/index.ecr"
end