Displaying validation errors in our forms

As of yet, we haven't actually hooked up any of this new shiny logic in our form, so if we try to submit anything we'll just see a generic error message that isn't very helpful. One thing that we left out of each of our forms is a per-field error message. Phoenix will helpfully wrap any errors inside of a span with a help-block class, so first let's open up assets/css/app.css and add the following code:

span.help-block {
color: #f00;
}

Next, we'll jump into our users form and start adding error_tag statements to each of our fields. Open up lib/vocial_web/templates/user/form.html.eex and follow along with each field update as follows:

  • Username:
<%= label f, :username, "Username:" %>
<br />
<%= text_input f, :username %>
<%= error_tag f, :username %>
  • Email:
<%= label f, :email, "Email:" %>
<br />
<%= text_input f, :email %>
<%= error_tag f, :email %>
  • Password:
<%= label f, :password, "Password:" %>
<br />
<%= password_input f, :password %>
<%= error_tag f, :password %>
  • Password Confirmation:
<%= label f, :password_confirmation, "Confirm your password:" %>
<br />
<%= password_input f, :password_confirmation %>
<%= error_tag f, :password_confirmation %>

Now let's return to the user creation form and add bad data in each of the fields to verify the results, as shown in the following screenshot:

We should also verify that creating two users with the same username fails. In that scenario, we should expect to see an error message underneath the Username field that says something along the lines of has already been taken, as shown in the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset