开发者

Can't validate phone number

I'm trying to validate a phone number without success. When I submit the form for the following model, it alwa开发者_StackOverflowys accepts the phone number I put in, whether it's valid or not. Why is this happening?

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 %>


You should be using validates_format_of instead of validates_presence_of. Something like:

validates_format_of :phone, 
                    :with => /\A[0-9]{10}\Z/, 
                    :allow_blank => true, 
                    :allow_nil => true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜