Rails7 stimulusを使用してフォームにバリデーションをかける
- 作成日 2024.07.03
- rails
![Rails7 stimulusを使用してフォームにバリデーションをかける](https://mebee.info/wp-content/uploads/2024/06/image-890x500.png)
Ruby on Rails 7で、stimulusを使用してフォームにバリデーションをかけるサンプルコードです。
環境
- OS Ubuntu24.04
- rails 7.1.3
Stimulusのインストール
Rails 7では、Stimulusがデフォルトでセットアップされているため、追加のインストールは不要ですが、念のため以下のコマンドで確認します。
$ bundle exec rails stimulus:install
Stimulusコントローラーの作成と設定
Stimulusコントローラーを生成します。これにより、app/javascript/controllers/form_validation_controller.js
が作成されます。
$ rails generate stimulus FormValidation
生成されたコントローラーを以下のように編集します。
// app/javascript/controllers/form_validation_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["email", "password", "emailError", "passwordError"]
validate() {
this.clearErrors();
let isValid = true;
if (!this.emailTarget.value.includes("@")) {
this.emailErrorTarget.textContent = "Invalid email address";
isValid = false;
}
if (this.passwordTarget.value.length < 6) {
this.passwordErrorTarget.textContent = "Password must be at least 6 characters long";
isValid = false;
}
if (isValid) {
this.element.submit();
}
}
clearErrors() {
this.emailErrorTarget.textContent = "";
this.passwordErrorTarget.textContent = "";
}
}
HTMLの設定
ビューファイルでStimulusコントローラーを使用します。
<!-- app/views/welcome/index.html.erb -->
<h1>Sign Up</h1>
<form data-controller="form-validation" data-action="submit->form-validation#validate">
<div>
<label for="email">Email:</label>
<input id="email" type="text" data-form-validation-target="email">
<span data-form-validation-target="emailError" class="error"></span>
</div>
<div>
<label for="password">Password:</label>
<input id="password" type="password" data-form-validation-target="password">
<span data-form-validation-target="passwordError" class="error"></span>
</div>
<button type="submit">Sign Up</button>
</form>
ルートの設定
config/routes.rb
でルートを設定します。
# config/routes.rb
Rails.application.routes.draw do
root 'welcome#index'
end
Railsサーバーの起動
最後に、Railsサーバーを起動して動作を確認します。
※自分の環境は外部からアクセスできるようにして起動してます。
$ rails s -b 0.0.0.0
これでバリデーションがかかっていることが確認できます。
![](https://mebee.info/wp-content/uploads/2024/06/rails7-1.gif)
-
前の記事
kotlin インターフェイスを作成する 2024.07.01
-
次の記事
Dart リスト(配列)の最初の値を取得する 2024.07.03
コメントを書く