Ich arbeite an einem einfachen einseitigen Kontaktformular. Kontakt-Modell haben zwei Attribute: Telefon und E-Mail. E-Mail sollte am Backend validiert werden (ich habe es in meinem Modell getan). Aber Benutzer können entweder E-Mail oder Telefon in das Kontaktformular ausfüllen und senden. Kein E-Mail-Feld in notwendig und ich weiß nicht, wie man es optional macht.Wie validiere ich E-Mails im Backend (Rails) und erlaube es nicht, dieses Feld im Formular zu füllen?
contact.rb
class Contact < MailForm::Base
attribute :phone
attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i,
presence: false
def headers
{
:subject => "My Contact Form",
:to => "[email protected]",
:from => %("#{phone}" <#{email}>)
}
end
Ende
contacts_controller.rb
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
@contact.request = request
if @contact.deliver
flash.now[:notice] = 'Ваша заявка принята!'
render :new
else
flash.now[:notice] = 'Введите корректный email.'
render :new
end
end
private
def contact_params
params.require(:contact).permit(:phone, :email)
end
end
new.html.erb
<%= simple_form_for @contact, html: {class: 'form-inline'} do |f| %>
<div class="form-group">
<div class="col-sm-6">
<%= f.input_field :email, class: "form-control", placeholder: "email", required: false %>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<%= f.input_field :phone, class: "form-control", placeholder: "+7 (095) 123-45-67" %>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<%= f.button :submit, 'Submit', :class=> "btn btn-success" %>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<% flash.each do |key, value| %>
<div class="alert alert-info" role="alert">
<div class="alert alert-<%= key %>"><%= value %></div>
</div>
<% end %>
</div>
</div>
<% end %>
Enthält diese den Anwender bedeuten könnte entweder das Telefon oder E-Mail eingeben, während ein passieren ist erforderlich? Oder möchten Sie die E-Mail nur bestätigen, wenn sie vorhanden ist? – oreoluwa