我正在尝试验证电话号码但未成功。当我提交以下型号的表格时,它总是接受我输入的电话号码,无论它是否有效。为什么会这样?
class Client < ActiveRecord::Base
belongs_to :salon
belongs_to :address
accepts_nested_attributes_for :address
attr_accessible :address_attributes, :name, :phone, :email
validates_presence_of :name
validates_presence_of :email
validates_presence_of :phone,
:unless => Proc.new { |c| c.phone.gsub(/[^0-9]/, "").length != 10 }
end
-
<%= form_for(@client) do |f| %>
<% if @client.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@client.errors.count, "error") %> prohibited this client from being saved:</h2>
<ul>
<% @client.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :salon_id, :value => Salon.logged_in_salon.id %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :phone %><br />
<%= f.text_field :phone %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<%= f.fields_for :address do |address_form| %>
<div class="field">
<%= address_form.label :line1 %><br />
<%= address_form.text_field :line1 %>
</div>
<div class="field">
<%= address_form.label :line2 %><br />
<%= address_form.text_field :line2 %>
</div>
<div class="field">
<%= address_form.label :city %><br />
<%= address_form.text_field :city %>
</div>
<div class="field">
<%= address_form.label :state_id %><br />
<%= select("client[address]", "state_id", State.all.collect {|s| [ s.name, s.id ] }) %>
</div>
<div class="field">
<%= address_form.label :zip %><br />
<%= address_form.text_field :zip %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:2)
您应该使用validates_format_of
代替validates_presence_of
。类似的东西:
validates_format_of :phone,
:with => /\A[0-9]{10}\Z/,
:allow_blank => true,
:allow_nil => true