Ruby on Rails ActiveRecord Validations Validates format of an attribute


Example

Validate that an attribute's value matches a regular expression using format and the with option.

class User < ApplicationRecord
  validates :name, format: { with: /\A\w{6,10}\z/ }
end

You can also define a constant and set its value to a regular expression and pass it to the with: option. This might be more convenient for really complex regular expressions

PHONE_REGEX = /\A\(\d{3}\)\d{3}-\d{4}\z/
validates :phone, format: { with: PHONE_REGEX }

The default error message is is invalid. This can be changed with the :message option.

validates :bio, format: { with: /\A\D+\z/, message: "Numbers are not allowed" }

The reverse also replies, and you can specify that a value should not match a regular expression with the without: option