简体   繁体   中英

Rails 4 remove some validation error messages but not all

I want my validation message to no matter what error be simply the following:

"example: (415) 944-2099"

I have the following in my model

  validates :phonenumber, presence: {is: true, message: " "},
                          format: {with: VALID_PNUM_REGEX, message: "example: (415) 944-2099" },
                          length: {in: 10..15, message: " "}

The above code though displays the following (if the field is left blank, therefore not matching any of the requirements): ", example: (415) 944-2099,"

How do I get rid of the commas or simply make my own overall validation message?

Try this validator in your model:

validate :phone_validator

def phone_validator
  if phonenumber.blank? || !phonenumber.match(VALID_PNUM_REGEX) || !phonenumber.length.in?(10..15)
    self.errors.add(:phonenumber, 'example: (415) 944-2099')
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM