検証機能やがね
検証機能(バリデーション(バリィさん))をいれてみる。
検証ルールは基本的にはモデルクラス(モデル名.rb)に宣言するのが基本。
かきかたの例
validates :isbn, presence: true, #必須検証 uniqueness: true, #一意検証 length: {is: 17}, #文字列長検証(17文字) format: {with: /¥A[0-9]{3}-[0-9]{1}-[0-9]{3,5}-[0-9]{4}-[0-9X]{1}¥z/ } #正規表現検証 validates :price, numericality: {only_integer: true, less_than: 10000} #数値検証(整数、10000未満) validates :publish, inclusion: {in: ['ほげ社', 'ほげほげ社', 'hogehogeシステム', 'ho-gege']} #候補値検証
みたいな感じ。
scaffoldの場合、controller部分で成功/失敗の場合分けされている。
検証エラーを表示しているのは_form.html.erb
具体的には
<% if @table.errors.any? %>
以下の部分。
で、エラー表示のdiv要素には「field_with_errors」クラスが付与される。
このクラスはscaffolds.css.scssに記載されてる。
.field_with_errors { padding: 2px; background-color: red; display: table; }
デフォルトだとこんな感じ。
そのままだとエラー感バリバリの表示になる。要修正。