class Book < ActiveRecord::Base
validates :isbn,
:presence => true, # 空チェック
:uniqueness => true, # 一意チェック
:length => { :is => 17 }, # 文字数チェック
:format => { :with => /^[0-9-]*$/ } # 正規表現チェック
validates :price,
:numericality => { :only_integer => true, :less_than => 10000 } # 数値チェック
end
<% if @book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div id="error_explanation">
<h2>2 errors prohibited this book from being saved:</h2>
<ul>
<li>Isbn is the wrong length (should be 17 characters)</li>
<li>Price must be less than 10000</li>
</ul>
</div>
<div class="field"> <div class="field_with_errors"><label for="book_isbn">Isbn</label></div><br /> <div class="field_with_errors"><input id="book_isbn" name="book[isbn]" size="30" type="text" value="978-4-7980-2812" /></div> </div> <div class="field"> <label for="book_title">Title</label><br /> <input id="book_title" name="book[title]" size="30" type="text" value="" /> </div> <div class="field"> <div class="field_with_errors"><label for="book_price">Price</label></div><br /> <div class="field_with_errors"><input id="book_price" name="book[price]" size="30" type="number" value="1000000" /></div> </div>
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
| :inclusion | 候補チェック | |
| :acceptance | 利用規約とかの同意チェック | DBにカラム不要 |
| :confirmation | 別項目との同一チェック | パスワードの再入力など、DBカラム不要 |
| :uniqueness | 一意性チェック | 複数カラムをwhere句みたいに指定も可能 |
# coding: utf-8 class IsbnValidator < ActiveModel::EachValidator def validate_each( record, attribute, value ) record.errors.add(attribute, 'は正しく無いよ!') unless value =~ /^[0-9-]*$/ end end
class Book < ActiveRecord::Base validates :isbn, :isbn => true, # ここが自作バリデートね :presence => true, # 空チェック
field = record.title
field = record.attributes[options[:compare_to]]
class Book < ActiveRecord::Base validate :title_valid? private def title_valid? errors.add(:title, 'は空じゃ駄目だよ!') unless !title.empty? end ----以下略----