在Ruby on Rails中,表单验证是通过Active Record模型来实现的。以下是一些常见的表单验证方法和示例:
class User < ApplicationRecord validates :name, presence: true end
class User < ApplicationRecord validates :name, length: { minimum: 3, maximum: 50 } end
class User < ApplicationRecord validates :email, format: { with: /\A[^@\s]+@[^@\s]+\z/, message: "must be a valid email address" } end
class Product < ApplicationRecord validates :price, numericality: { greater_than: 0 } end
class Order < ApplicationRecord validates :size, inclusion: { in: %w(small medium large) } end
class User < ApplicationRecord validates :email, uniqueness: true end
你还可以创建自定义验证方法来满足特定需求。
class User < ApplicationRecord
validate :name_is_acceptable
private
def name_is_acceptable
if name.blank? || name.include?('admin')
errors.add(:name, 'is not acceptable')
end
end
end
在视图中显示验证错误信息通常使用 @user.errors.full_messages
。
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
以下是一个简单的表单示例,使用 Rails 的 form_with
助手。
<%= form_with(model: @user, local: true) do |form| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.email_field :email %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
通过这些方法,你可以在 Ruby on Rails 中轻松实现表单验证。
领取专属 10元无门槛券
手把手带您无忧上云