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.
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.
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.
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.
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.
Ah, it was easy :required => true
eg: <%=t.text_area :content, :rows => 3, :required => true%>
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}' %>
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With