Form validation can be annoying, with all the error message styling and all. Heres an easy solution I just stumbled across. Note that this works best for when starting new apps, but should still plugin quite nicely into old ones.
Setup:
I will be using this javascript library for validation. I use the styling from Bootstrap to make it look extra pro.
Get the Javascript file
Here is a slightly nerdy terminal way of getting it. I like it because when you use it again in future you just can go “git pull” and get the latest version.
$ cd into your favourite place to keep jquery plugins
$ git clone https://github.com/victorjonsson/jQuery-Form-Validator.git
$ cd jQuery-Form-Validator/
$ cp jquery.formvalidator.min.js path-to-rails-app/vendor/assets/javascripts/
# application.js
...
#= require jquery.formvalidator.min.js
...
Styling
/* application.css */
...
*= require bootstrap
...
/* Here is some extra styling for the plugin. Basically it puts the error message just below the text field. */
/* styles.css.scss */
.jquery_form_error_message{
display: block;
margin-top: 3px;
}
The form markup
I’d only look at this if you are using Bootstrap, as this is based on their CSS.
Notice the data-validation attribute in the input element? This is where you specify cool validation stuff – check out the github page for a list of options.
<fieldset>
<legend>Sign up</legend>
<div class="clearfix">
<label for="email_field">Email</label>
<div class="input">
<input data-validation="validate_email" id="email_field" type="text" name="user[email]" value="" placeholder="Email">
</div>
</div>
<div class="clearfix">
<label for="first_name_field">First Name</label>
<div class="input">
<input data-validation="required validate_min_length length4" id="first_name_field" type="text" name="user[first_name]" value="" placeholder="First name">
</div>
</div>
etc...
