HTML5 'required' validation in Ruby on Rai

2020-05-19 03:32发布

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.

8条回答
家丑人穷心不美
2楼-- · 2020-05-19 04:18

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}' %>

:)

查看更多
戒情不戒烟
3楼-- · 2020-05-19 04:21

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.

查看更多
登录 后发表回答