5
1

More than 3 years have passed since last update.

priceのバリデーションを半角数字だけ適応したい

Last updated at Posted at 2021-07-12

はじめに

投稿内容に金額(price)を入力する欄を作りました。

しっかり半角数字のバリデーションを定義したのに全角でも入力できてしまったので解消法を投稿します。

やってしまったミス

class Review < ApplicationRecord
  with_options presence: true do
    validates :faclity_name, length: { maximum: 40 }
    validates :images
    validates :price, format: { with: /\A[0-9]+\z/ }
  end
end

このようにpriceに空だと投稿できない、半角数字でなければ投稿できないバリデーションを定義しました。

しかし全角文字でも投稿ができてしまいました。

解決方法

数値のみというバリデーションがありました。

numericality:

今回は0円から9,999,999円までまでは投稿できる設定にしたいので以下のように記述しました。

validates :price, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 9_999_999 },
                  format: { with: /\A[0-9]+\z/ }
5
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1