1.前期准备工作:
gem 'client_side_validations'
# 生成 config/initializers/client_side_validations.rb
$ rails g client_side_validations:install
# app/assets/javascripts/application.js 添加:
(如果有 turbolinks,添加在这之后)
//= require rails.validations
- start(与SimpleForm兼容,举例(haml):form_for)
在config/initializers/client_side_validations.rb添加
ActionView::Base.field_error_proc = proc do |html_tag, instance|
if html_tag =~ /^<label/
%(<div class="field_with_errors">#{html_tag}</div>).html_safe
else
%(<div class="field_with_errors">#{html_tag}<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}</label></div>).html_safe
end
end
验证提示可以自由设定
form表单(添加“validate: true”,form表单需要验证的也需要添加validate: true/false,或者特别设定类似:validate: { presence: true }
提交结果):
= form_for(@user, validate: true, :defaults=>{ input_html: {class: 'form-control'},
html: {class: "form-inline", role: "form"} }) do |f|
- if @user.errors.any?
- @user.errors.full_messages.each do |message|
%li= message
.row
.col-xs-6
.table-responsive
%table.table.table-bordered.table-hover
%tr
%th= f.label 'name:'
%td= f.text_field :name, validate: false
-#%td= f.input_field :name, validate: { presence: true }
%tr
%th= f.label 'password:'
%td= f.text_field :password, validate: true
%tr
%th= f.label 'email:'
%td= f.text_field :email, validate: true
%tr
%td.text-center{colspan: 2}
= f.submit 'confirm', :class=>'btn btn-primary'
自己测试截图:
实测:未经过controller, 实现前端验证