Reputation: 1408
Hi I am new to rails and have the following rails form, which works fine.
<%= form_for :user, url: users_path do |f| %>
<p>
<%= f.text_field :email, :placeholder=>'first name' %>
<%= f.text_field :email, :placeholder=>'last name' %>
<%= f.email_field :email, :placeholder=>'email address' %>
<%= f.password_field :password, :placeholder=>'password' %>
<%= f.password_field :password2, :placeholder=>'password2' %>
</p>
<%= f.submit 'Sign up!', :class=>'btn-custom btn-submit' %>
<% end %>
On the email textbox there is some client side validation built into it which will not submit the form and highlight the field if it detects a string that isn't the format of an email address.
For some reason the built in form validation doesn't check whether the text fields are empty. Is there a rails way to make it check that?
I understand that I could do it with jquery and will do it that way if there is no other way but it seems silly to have 2 separate forms of validation code.
fyi I also have validation on my model.
Upvotes: 3
Views: 4646
Reputation: 6096
Why have you got :email
on every line here?
<%= f.text_field :email, :placeholder=>'first name' %>
^^^^^^ Here
<%= f.text_field :email, :placeholder=>'last name' %>
^^^^^^^ and here
<%= f.email_field :email, :placeholder=>'email address' %>
Shouldn't they be called :firstname
and :lastname
? (or whatever the attributes are called in your model.)
I'm not sure what kind of validation you're talking about. If you mean client-side validation, i.e. to prevent the form from submitting at all if there are blank fields, this has to be done through Javascript. Rails is server-side code so can't do anything with the form data until it's already been submitted.
To validate the fields server side you'd just add something like this in your model:
validates :email, presence: true
validates :firstname, presence: true
validates :lastname, presence: true
... which you say you've already done, but I'm including this for full reference for anyone who might be reading this question in the future.
Upvotes: 2
Reputation: 6786
use this:
<%= f.email_field :email, :required => true, :pattern => '[^@]+@[^@]+\.[a-zA-Z]{2,6}', :placeholder=>'email address' %>
Moreover:
you have these:
<%= f.text_field :email, :placeholder=>'first name' %>
<%= f.text_field :email, :placeholder=>'last name' %>
I guess it should be
<%= f.text_field :first_name, :placeholder=>'first name' %>
<%= f.text_field :last_name, :placeholder=>'last name' %>
Upvotes: 7