How to add validation to contact form? - ruby-on-rails

I am trying to add a contact form for users to fill and it will automatically email to the main account. I am unsure as to how I can add validation to the form so users are not able to click "Send Email" without filling in the fields.
I have currently tried adding Website: <input type="url" name="website" required>
app/views/contact_mailer/contact_email.html.erb:
<!DOCTYPE html>
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
</head>
<body>
<h1>Contact Us Form</h1>
<p>
From: <%= #params['name'] %>
</p>
<p>
Email: <%= #params['email'] %>
</p>
<p>
Message: <%= #params['message'] %>
</p>
</body>
</html>
Contact form:
<h1>Any enquiries:</h1>
<center><form name="htmlform" method="get" action="/pages/send_form">
<table width="700px">
<form id="contact_form" action="#" method="POST" enctype="multipart/form-data">
<div class="row">
<label for="name">Your Name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="30" /><br />
</div>
<div class="row">
<label for="email">Your Email:</label><br />
<input id="email" class="input" name="email" type="text" value="" size="30" /><br />
</div>
<div class="row">
<label for="message">Your Message:</label><br />
<textarea id="message" class="input" name="message" rows="7" cols="30"></textarea><br />
</div>
<input id="submit_button" type="submit" value="Send email" />
</form>
Currently, the email still sends to the account without any validation such as "You must complete this field"

Create a model for your contact message. Something like:
class ContactEmail
attr_accessor :name, :email, message
end
Then include ActiveModel::Model to get ActiveModel's validation and tell the model which fields to validate, like:
class ContactEmail
include ActiveModel::Model
attr_accessor :name, :email, message
validates :name, :email, message, presence: true
end
Finally, in your controller action, create a new ContactEmail with the form data and call the predicate method valid?. And use flash to add an error message.
new_mail = ContactEmail.new(params['name'], params['email'], params['message'])
if new_mail.valid?
...
else
flash.now[:error] = new_mail.errors.full_messages
end

Could you use the HTML form attributes? There is a required attribute so the user can't leave the field empty.
e.g.,
<input required id="email" class="input" name="email" type="email" value="" size="30" />
you can also use the type = "email" and it will ensure some of the proper formatting.
(https://www.w3schools.com/html/html_form_attributes.asp)

Looking at the code of your form i see several problems:
you have 2 <form> openings
i dont see any file inputs so you don't need the enctype="multipart/form-data"
here's the code revised (i've removed the first form element, i've adjusted the action of the second form, i've added required attributes to the inputs and textarea and i've updated the email input's type to "email" to make sure only valid emails are entered). Adding required should force modern browsers to prevent form submission if the inputs are not filled in properly.
<h1>Any enquiries:</h1>
<center>
<table width="700px">
<form id="contact_form" action="/pages/send_form" method="POST">
<div class="row">
<label for="name">Your Name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="30" required /><br />
</div>
<div class="row">
<label for="email">Your Email:</label><br />
<input id="email" class="input" name="email" type="email" value="" size="30" required /><br />
</div>
<div class="row">
<label for="message">Your Message:</label><br />
<textarea id="message" class="input" name="message" rows="7" cols="30" required></textarea><br />
</div>
<input id="submit_button" type="submit" value="Send email" />
</form>

Related

Why "href" and "th:href" exist at the same time?

I am reading a page using Thymeleaf.
In "Edit page", there is a "Back" button for going back to "User List Page". The strange thing for me is this button has "href" and "th:href" at the same time.
image detail of the button
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>user</title>
<link rel="stylesheet" th:href="#{/css/bootstrap.css}"></link>
</head>
<body class="container">
<br/>
<h1>修改用户</h1>
<br/><br/>
<div class="with:80%">
<form class="form-horizontal" th:action="#{/edit}" th:object="${user}" method="post">
<input type="hidden" name="id" th:value="*{id}" />
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">userName</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="userName" id="userName" th:value="*{userName}" placeholder="userName"/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label" >Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" id="password" th:value="*{password}" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">age</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Submit" class="btn btn-info" />
Back
</div>
</div>
</form>
</div>
</body>
</html>
It is obvious that "th:href" is for going back. Is there any opition on what is the function of the atrribute "href"?
ThymeLeaf is designed to use the same file for both as prototype you can view in your browser as well as a working template file. What this means in practice is that if you want, you can open the template file in a browser without actually running it and it still looks okay. For example, in this code:
Back
If you open the file directly in a browser, the browser will ignore the th:href (because it doesn't know what to do with it) and instead use href="/toAdd". However, when you run it through the templating engine on a server, href="/toAdd" is replaced with the result of the dynamic expression th:href="#{/list}".
This is more easily shown with a table. Like this:
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
When you open that in a browser, you'll see a table with a single row (Onions, 2.41, yes). But when you run it through the server, the actual content of the table is replaced with whatever data exists in the ${prods} variable.

Get method : form input not in url

I am doing my first ASP.NET mvc project, on the home page, Index.cshtml, I have a small form:
<form action="ChoixFormulaire" method="get">
<fieldset>
<label>NAS</label>
<input id="nas" type="text" placeholder="###"/>
<br />
<label>Date of birth</label>
<input id="date" type="text" placeholder="AAAA-MM-JJ"/>
<br />
<label>Employee number</label>
<input id="numEmployee" type="text" placeholder="######"/>
<br />
</fieldset>
<input type="submit" value="Soumettre" onclick="return VerifierFormulaire()" />
</form>
When the button is clicked, there is some verification made in the 'VerifierFormulaire()' method, which is defined in the same Index.cshtml file. Then the ChoixFormulaire.cshtml is displayed (called from the ChoixFormulaire() method in my HomeController, which returns View()).
I was expecting the form inputs to be in the URL as parameters. For example, If I enter '123' for NAS, '1989-01-01' for date of birth and '123456' for employee number, I am redirected to http://localhost:15778/Home/ChoixFormulaire? but I would expect to be redirected to http://localhost:15778/Home/ChoixFormulaire?nas=123&dateBirth=1989-01-01&numEmployee=123456
Try adding the name attribute:
<input id="nas" name="nas" />

Ruby on Rails param is missing or the value is empty without using a model

In my contact.html, I have this code
<div class="form">
<form name="email-form" method="POST">
<label class="field-label" for="name">Name:</label>
<input class="w-input text-field-2" id="name" type="text" name="name" data-name="Name" required="required">
<label class="field-label" for="Email">Email:</label>
<input class="w-input text-field-2" id="email" type="email" name="email" data-name="Email" required="required">
<label class="field-label" for="Subject">Subject:</label>
<input class="w-input text-field-2" id="subject" type="text" name="subject" data-name="Subject">
<label class="field-label" for="Content">Text Message:</label>
<textarea class="w-input text-field-2 area" id="content" name="content" data-name="Text Area" required="required"></textarea>
<div>
<input class="w-button button" type="submit" value="Submit Message" data-wait="Please wait...">
</div>
</form>
</div>
This is under my controller
def contact
end
def send_mail
MessageMailer.new_message(contact_params).deliver
redirect_to contact_path, notice: 'Your messages has been sent.'
end
private
def contact_params
params.require(:contact).permit(:name, :email, :subject, :content)
end
under mailers/message_mailer.rb
class MessageMailer < ActionMailer::Base
default from: "sys.questdentalusa#gmail.com"
default to: "questdentalusa#gmail.com"
def new_message(contact)
#contact = contact
mail subject: #contact.subject
end
end
and under my new_message.text.erb is this code
Name: <%= #contact.name %>
Email: <%= #contact.email %>
Message: <%= #contact.content %>
I am to send an email consisting user's name, email and message which is inputed and NOT saved in the database. When I pass the four parameters like this
def send_mail
MessageMailer.new_message(:name, :email, :subject, :content).deliver
redirect_to contact_path, notice: 'Your messages has been sent.'
end
it worked just fine but i was told to use only one parameter, seems like group the four parameters: name, email, subject, content as one (contact)
When I typed the info and hit the submit button, I get this error message
param is missing or the value is empty: contact
I presume that what caused this error is because my def contact is empty. So I added contact.new and #contact=contact.new and MessageMailer.new but this error occurs NoMethodError
How can I possibly fix this? What should I write under my def contact ?
Your controller code is correct. You don't need Contact.new or something. The problem is with your <form>. What ends up in params depends on your form and in your form you don't have contact.
Instead of:
<input type="text" name="subject">
You have to do something like this:
<input type="text" name="contact[subject]">
And that for all the fields on your contact form.
Another option would be to use Rails' form helpers.
contact[] is missing in your form, see below correct one:
<div class="form">
<form name="email-form" method="POST">
<label class="field-label" for="name">Name:</label>
<input class="w-input text-field-2" id="name" type="text" name="contact[name]" data-name="Name" required="required">
<label class="field-label" for="Email">Email:</label>
<input class="w-input text-field-2" id="email" type="email" name="contact[email]" data-name="Email" required="required">
<label class="field-label" for="Subject">Subject:</label>
<input class="w-input text-field-2" id="subject" type="text" name="contact[subject]" data-name="Subject">
<label class="field-label" for="Content">Text Message:</label>
<textarea class="w-input text-field-2 area" id="content" name="contact[content]" data-name="Text Area" required="required"></textarea>
<div>
<input class="w-button button" type="submit" value="Submit Message" data-wait="Please wait...">
</div>
</form>
</div>

Redirect to a specific site after login via spring security

I have coded a sign up page:
<div class="container">
<div class='fheader'>
<g:message code="springSecurity.login.header" />
</div>
<g:if test='${flash.message}'>
<div class='login_message'>
${flash.message}
</div>
</g:if>
<form action='${postUrl}' method='POST' id='loginForm'
class="form-signin" autocomplete='off'>
<h2 class="form-signin-heading">Please sign in</h2>
<input type='text' class="form-control" name='j_username'
id='username' placeholder="Username" /> <input type='password'
class="form-control" name='j_password' id='password'
placeholder="Password" />
<p id="remember_me_holder">
<input type='checkbox' class='checkbox'
name='${rememberMeParameter}' id='remember_me'
<g:if test='${hasCookie}'>checked='checked'</g:if> /> <label
class="checkbox" for='remember_me'><g:message
code="springSecurity.login.remember.me.label" /></label>
</p>
<!-- <label class="checkbox"> <input type="checkbox"
value="remember-me"> Remember me
</label> -->
<input class="btn btn-lg btn-primary btn-block" type='submit'
id="submit" value='${message(code: "springSecurity.login.button")}' />
</form>
</div>
<!-- /container -->
<script type='text/javascript'>
<!--
(function() {
document.forms['loginForm'].elements['j_username'].focus();
})();
// -->
</script>
Into the page I have integrated the spring-security-core:2.0-RC2 plugin.
However, when I start the server and try to log in with my created users I get nothing. No notification that it worked, no redirect.
In fact I just want to redirect to my main page mapped as "/"(view:"/index") in the URLMappings.groovy
How to change the redirect?
I really appreciate your answer!
In your config file:
grails.plugins.springsecurity.successHandler.defaultTargetUrl="/someController/someAction"

Can't select checkbox using id in Capybara

There is the following RSpec code:
describe 'with valid information' do
it 'should create a new restaurant' do
visit new_restaurant_path
fill_in I18n.translate(:name), with: "Some restaurant"
fill_in I18n.translate(:address), with: "Some address of the restaurant"
fill_in I18n.translate(:average_check), with: 100
check('place_restaurant_food_types_1')
expect { click_button :submit }.to change(Restaurant, :count).by(1)
end
end
But I always get error "cannot check field, no checkbox with id, name, or label 'place_restaurant_food_types_1' found". I tried to replace id for name, but it was still the same. I'm absolutely sure that there is the item with needed id! (I copied it from the page source). How can I fix it?
HTML:
<form accept-charset="UTF-8" action="/restaurants" class="new_place_restaurant" id="new_place_restaurant" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="7yQCirO7MLO6e+Nj46eCSNUjQWd67MJVDIHmUV6/5Y0=" /></div>
<div class="row">
<label for="place_restaurant_name">Название</label>
<input id="place_restaurant_name" name="place_restaurant[name]" size="30" type="text" />
</div>
<div class="row">
<label for="place_restaurant_address">Адрес</label>
<input id="place_restaurant_address" name="place_restaurant[address]" size="30" type="text" />
</div>
<div class="row">
<label for="place_restaurant_average_check">Средний чек</label>
<input id="place_restaurant_average_check" name="place_restaurant[average_check]" size="30" type="text" />
</div>
<div class="row">
<input id="place_restaurant_food_types_1" name="place_restaurant[food_types][1]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_1">Восточная кухня</label>
</div>
<div class="row">
<input id="place_restaurant_food_types_2" name="place_restaurant[food_types][2]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_2">Национальная кухня</label>
</div>
<div class="row">
<input id="place_restaurant_food_types_3" name="place_restaurant[food_types][3]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_3">Японская кухня</label>
</div>
<div class="row">
<input id="place_restaurant_food_types_4" name="place_restaurant[food_types][4]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_4">Китайская кухня</label>
</div>
<div class="row">
<input id="place_restaurant_food_types_5" name="place_restaurant[food_types][5]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_5">Европейская кухня</label>
</div>
<div class="row">
<input id="place_restaurant_food_types_6" name="place_restaurant[food_types][6]" type="checkbox" value="1" />
<label for="place_restaurant_food_types_6">Кавказская кухня</label>
</div>
<div id="map_canvas"></div>
<input id="latitude" name="place_restaurant[latitude]" type="hidden" value="54.352271" />
<input id="longitude" name="place_restaurant[longitude]" type="hidden" value="48.52652" />
<div class="row">
<input id="submit" name="commit" type="submit" value="Сохранить" />
</div>
</form>
You could just use
check("place_restaurant_food_types_1")
as shown in the docs:
The check box can be found via name, id or label text.
Try By Xpath like this
find(:xpath, "//*[#id='place_restaurant_food_types_1']").click
You can use like this
find(:css,"input[id='place_restaurant_food_types_1']").set true

Resources