· 1 min read

Screencast: Validieren mit Rails 3

Download:

Download (14.4 MB, 9:53) Alternativer Download für iPod & Apple TV (14.3 MB, 9:53)

Resourcen:

Quellcode:

[bash] gem install rails —pre gem cleanup rails store cd store rails g scaffold user name:string email:string rake db:migrate [/bash]

[html] <%= form_for(@user) do |f| %> <%= render “shared/error_messages”, :target => @user %>

<%= f.label :name %><%= mark_required(@user, :name) %>
<%= f.text_field :name %>
<%= f.label :email %><%= mark_required(@user, :email) %>
<%= f.text_field :email %>
<%= f.submit %>
<% end %>

<% if target.errors.any? %>

<%= pluralize(target.errors.count, "error") %> prohibited this record from being saved:

    <% target.errors.full\_messages.each do |msg| %>
  • <%= msg %>
  • <% end %>
<% end %> \[/html\]

[ruby] # application_helper.rb def mark_required(object, attribute) ”*” if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator end

# models/user.rb validates :email, :presence => true, :uniqueness => true, :email_format => true

# lib/email_format_validator.rb class EmailFormatValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) unless value =~ /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || “is not formatted properly”) end end end [/ruby]

Back to Blog