Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 'required' validation in Ruby on Rails forms

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.

like image 841
LpLrich Avatar asked Nov 24 '12 14:11

LpLrich


People also ask

Does HTML5 have form validation?

Using HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation.

How do I bypass HTML5 validations?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

Which HTML5 attribute is used for data validation?

The pattern attribute of the <input> element allows you to add basic data validation without resorting to JavaScript. It works by matching the input value against a regular expression. A regular expression is a formalized string of characters that define a pattern.

What is the HTML5 form Validation API?

HTML5 Field ValidationModern HTML5 browsers can validate fields without JavaScript. A type attribute sets a constraint and can alter the UI of a standard <input> field: type. description. button.


2 Answers

Ah, it was easy :required => true

eg: <%=t.text_area :content, :rows => 3, :required => true%>

like image 79
LpLrich Avatar answered Oct 01 '22 05:10

LpLrich


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

:)

like image 40
prashantsahni Avatar answered Oct 01 '22 04:10

prashantsahni