<head>
<title>validate</title>
<style type="text/css">
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
.error_msg{
color: red;
font-weight: bold;
margin-top: 5px;
}
</style>
</head>
<body class="body_class">
<%= form_tag({action:'save'}, :method => :post, :id=>'image_form') do %>
用户名:
<%if @user.errors.any? && @user.errors[:acc_name].any?%>
<div class="field_with_errors">
<input type="text" id="acc_name" name="acc_name" value="<%=@user[:acc_name]%>" placeholder="">
</div>
<div class='error_msg'><%=@user.errors[:acc_name]%></div>
<%else%>
<div class="">
<input type="text" id="acc_name" name="acc_name" value="<%=@user[:acc_name]%>" placeholder="">
</div>
<%end%>
<br>
<br>
邮 箱:
<%if @user.errors.any? && @user.errors[:email].any?%>
<div class="field_with_errors">
<input type="text" id="email" name="email" value="<%=@user[:email]%>" placeholder="">
</div>
<div class='error_msg'><%=@user.errors[:email]%></div>
<%else%>
<div class="">
<input type="text" id="email" name="email" value="<%=@user[:email]%>" placeholder="">
</div>
<%end%>
<br>
<br>
确认邮箱:
<%if @user.errors.any? && @user.errors[:email_confirmation].any?%>
<div class="field_with_errors">
<input type="text" id="email_confirmation" name="email_confirmation" value="<%=@email_confirmation%>" placeholder="">
</div>
<div class='error_msg'><%=@user.errors[:email_confirmation]%></div>
<%else%>
<div class="">
<input type="text" id="email_confirmation" name="email_confirmation" value="<%=@email_confirmation%>" placeholder="">
</div>
<%end%>
<input type="submit" value='保存' />
<% end %>
</body>
</html>
class User < ActiveRecord::Base
validates_presence_of :acc_name, :message => "用户名不能为空!"
#validates :acc_name,:presence=>true
validates_presence_of :email, :message => "邮箱名不能为空!"
validates_presence_of :email_confirmation, :message => "确认邮箱不能为空!"
validates_format_of :email, :message => "邮箱格式不正确!", :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
validates_uniqueness_of :email, :message => "邮箱已存在!"
validates_confirmation_of :email, :message => "两次输入的邮箱不匹配!"
# validates :email, confirmation: true
validates_length_of :acc_name, :minimum => 3,:maximum => 6, :message => "用户名必须3到6个字符!"
#validates_length_of :acc_name, :in => 3..6, :message => "用户名必须3到6个字符!"
# validates :acc_name, length: { minimum: 3 }
def self.save(acc_name,email,email_confirmation)
user = User.new({acc_name:acc_name,email:email,email_confirmation:email_confirmation})
user.save
return user
end
end