V
V
V2016-07-07 02:33:00
Ruby on Rails
V, 2016-07-07 02:33:00

How to check email validation on the backend while making the email input field optional?

It is necessary to check email validation on the backend, while in the view the input field must be optional.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan, 2016-07-07
@mil0rd

  • Before validating the contents of the field, check for emptiness, if it is empty, skip it as a valid entry, then do the validation of what was indicated there.
    For myself, I made a validation class, and when checking, I specify a parameter to skip an empty (null) value.

V
V, 2016-07-10
@ermolushka

Solution found: in the model I wrote something like the following

class Contact < MailForm::Base
    attribute :phone
    attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i,
                          presence: false, allow_blank: true
    validate :at_least_a_contact

  def headers
    {
      :subject => "My Contact Form",
      :to => "[email protected]",
      :from => %("#{phone}" <#{email}>)
    }
  end
  private
    def at_least_a_contact
      unless phone.present? || email.present?
        errors.add(:contact, "You need at least a contact method")
      end
    end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question