如果用户注册,需要验证,该用户名也是客户端唯一的。
在gemfile中:
gem 'client_side_validations', github: 'DavyJonesLocker/client_side_validations', :branch => 'rails5'
client_side_validations.rb
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
unless html_tag =~ /^<label/
%{<div class="field_with_errors">#{html_tag}
<label for="#{instance.send(:tag_id)}" class="message">#{instance.error_message.first}
</label></div>}.html_safe
else
%{<div class="field_with_errors">#{html_tag}
</div>}.html_safe
end
end
模型用户
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_one :freelancer, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable
validates :username, uniqueness: true
end
注册/ new.html.erb
<div class="devise_page">
<div class="title_line">
<div class="right">
<%= link_to "Sign In", new_user_session_path %>
</div>
<div class="title">Registration</div>
</div>
<div class="login_page">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), validate: true, html: { class: "new_user"} ) do |f| %>
<div class="item">
<label for="user_email">E-mail</label>
<div class="field">
<%= f.email_field :email, autofocus: true, placeholder: "E-mail" %>
</div>
</div>
<div class="item">
<label>Nickname</label>
<div class="field">
<%= f.text_field :username, placeholder: "Nickname" %>
</div>
</div>
<div class="item">
<label>Password</label>
<div class="field">
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off", placeholder: "password" %>
</div>
</div>
<div class="item">
<label>Password again</label>
<div class="field">
<%= f.password_field :password_confirmation, autocomplete: "off", placeholder: "Password again" %>
</div>
</div>
<div class="buttons">
<%= f.submit "Sign up", class: "button button_green" %>
<div class="links">
<%= link_to "Forgot your password?", new_password_path(resource_name) %>
<%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
</div>
</div>
<% end %>
</div>
</div>
如果我输入的字段用户名不是唯一值,则客户端验证不起作用。