· 1 min read

Screencast: Clientseitige Validierung von Formularen

Download:

Download(20.2 MB, 8:42) Alternativer Download für iPod & Apple TV(19.3 MB, 8:42)

Resourcen:

Quellcode:

[bash] bundle rails g client_side_validations:install [/bash]

[ruby] # Gemfile gem ‘client_side_validations’

# models/user.rb validates_uniqueness_of :username, :email validates :email, :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.add(attribute, :email_format, options) end end end

# config/application.rb config.autoload_paths << ”#{config.root}/lib” [/ruby]

[html] <%= form_for @user, :validate => true do |f| %>

<%= javascript\_include\_tag :defaults, "rails.validations", "rails.validations.custom" %> \[/html\]

[text] # locals/en.yml en: errors: messages: email_format: “is not formatted properly” [/text]

[javascript] /* rails.validations.custom.js */ clientSideValidations.validators.local[“email_format”] = function(element, options) { if (!/^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i.test(element.val())) { return options.message; } } [/javascript]

Back to Blog