Skip to content

Instantly share code, notes, and snippets.

@jamesgecko
Created March 6, 2012 16:34
Show Gist options
  • Save jamesgecko/1987317 to your computer and use it in GitHub Desktop.
Save jamesgecko/1987317 to your computer and use it in GitHub Desktop.
Validation
<%= semantic_form_for([@customer, @phone]) do |f| %>
<%= f.semantic_errors :state %>
<%= f.inputs do %>
<%= f.input :number, as: :string, input_html: { maxlength: 18 }%><br />
<%= f.input :extension, as: :number %><br />
<%= f.input :number_type, as: :select, collection: Phone.number_type_name_options %>
<% end -%>
<%= f.actions %>
<% end %>
class Phone < ActiveRecord::Base
belongs_to :customer
attr_accessible :number, :number_type, :extension
NUMBER_TYPE_NAMES = {1 => 'Home', 2 => 'Work', 3=> 'Cell'}
def number_type_name
NUMBER_TYPE_NAMES[self.number_type]
end
def self.number_type_name_options
options = {}
NUMBER_TYPE_NAMES.sort.each {|i, v| options[v] = i }
return options
end
before_validation :strip_non_numeric
validates :number,
presence: true,
length: { minimum: 7, maximum: 11 },
numericality: { only_integer: true }
validates :extension,
allow_blank: true,
numericality: { only_integer: true }
validates :number_type,
allow_blank: false,
numericality: { only_integer: true }
protected
def strip_non_numeric
number.to_s.gsub! /\D/, ''
number = number.to_i
end
end
New phone
Number* [(123) 457 - 7890]
is too short (minimum is 7 characters) and is not a number
Extension [123]
Number type [Work |v]
Back
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment