LoginSignup
0
0

More than 1 year has passed since last update.

【rails】validateをかけてみた。

Posted at

バリデーションを設定

class User < ApplicationRecord

    #ハイフンあり、7桁の整数
    VALID_ZIPCODE_REGEX = /\A\d{3}[-]\d{4}\z/
    #メールアドレス
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    #電話番号 ハイフンあり、整数
    VALID_PHONE_REGEX = /\A[0-9-]+\z/

    validates :first_name, presence: true, length: { maximum: 10 } # 存在する、かつ、10文字以下。
    validates :last_name, presence: true, length: { maximum: 10 }
    validates :zipcode, presence: true, format: {with: VALID_ZIPCODE_REGEX }
    validates :prefecture, presence: true, length: { maximum: 5 }
    validates :municipality, presence: true, length: { maximum: 10 }
    validates :address, presence: true, length: { maximum: 10 }
    validates :email, presence: true, uniqueness: true, format: { with: VALID_EMAIL_REGEX }
    validates :phone_number, presence: true, length: { maximum: 15 }, format: { with: VALID_PHONE_REGEX }
    validates :password, presence: true, length: { minimum: 6, maximum: 15 }

    belongs_to :user_classification
    has_secure_password
end

苦戦したところ

電話番号の/\A[0-9-]+\z/ について、"9"の後の"-"によって、
0~9の数字と、"-"はOKになる。

ハイフンをどこに入れても許可する設定が中々分からなくて苦労した。

0
0
0

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
0
0