Reputation: 2533
I can't see this question anywhere else, it's hopefully a quick and easy one.
How can I use HTML5 validators, such as 'required', in my forms (ruby on rails)?
Eg, How would this basic form look if I used HTML5 validation in it?
<%=form_for @testimonial do |t|%>
<dl>
<dt><label for="testimonial_rating">Rating</label></dt>
<dd><%=t.select :rating, Testimonial.ratings%></dd>
<dt><label for="testimonial_content">Comments</label></dt>
<dd><%=t.text_area :content, :rows => 3%></dd>
<dd><button class="button success">Submit Review</button></dd>
</dl>
<%end%>
It goes without saying that server side validation is still required.
Upvotes: 71
Views: 83467
Reputation: 378
Use this if nothing works
include_blank: false, required: true
Upvotes: 1
Reputation: 891
New Syntax
<%= f.text_field :email, class: "form-control", required: true %>
Upvotes: 5
Reputation: 41
For completing other answers, there is an awesome gem html5_validations which makes the most of the HTML5 validations reading from ActiveRecord Validations from the model. No extra code needed, just installing it.
Upvotes: 3
Reputation: 2776
This is a little example with the common attributes and for required you only add required:true, but dont forget apply this validations in your backend.
<%= f.text_field
id: "yourID",
class: "yourCLass",
placeholder: "Your message",
maxlength: 14,
required: true
%>
Upvotes: 5
Reputation: 1082
Addition to @prashantsahni answer. You can also use type = 'email' instead of regex pattern, then your erb-template will look like this:
<%= f.email_field :email, id: 'user_email', type:'email', required: true, placeholder: "Email" %>
More info about form validations using html5
Upvotes: 11
Reputation: 2533
Ah, it was easy :required => true
eg: <%=t.text_area :content, :rows => 3, :required => true%>
Upvotes: 119
Reputation: 2195
Just to add on, if you have an email field, you can also use 'pattern' attribute to validate the format of email
<%=form.text_field :email, :required => true, :pattern => '[^@]+@[^@]+\.[a-zA-Z]{2,6}' %>
:)
Upvotes: 42
Reputation: 5236
This could be easily done by adding :required => true
parameter into your input fields:
For example
f.text_field :first_name, :required => true
text_field_tag :first_name, nil, :required => true
Pushing the boundary abit further, you could add in pattern matcher for your input, such as email:
f.email_field :email, 'Email', :required => true, :pattern => '[^@]+@[^@]+\.[a-zA-Z]{2,6}'
Upvotes: 4