Rendering validation error messages

In this section, we are going to render the validation error messages in the Field component:

  1. Let's display all errors in a span with the form-error CSS class we have already implemented. We display these at the bottom of the div container of the form-group:
<div className="form-group">
<label htmlFor={name}>{label}</label>
{(type === "Text" || type === "Email") && (
...
)}
{type === "TextArea" && (
...
)}
{type === "Select" && (
...
)}
{context.errors[name] &&
context.errors[name].length > 0 &&
context.errors[name].map(error => (
<span key={error} className="form-error">
{error}
</span>
))}
</div>

So, we first check that we have errors for the field name, and then use the map function in the errors array to render a span for each error.

  1. We have referenced a CSS form-error class, so let's add this to index.css:
.form-error {
font-size: 13px;
color: red;
margin: 3px auto 0px 0px;
}

It's time to give the Contact Us page a try. If our app isn't started, start it using npm start and go to the Contact Us page. If we tab through the name and email fields, the required validation rule triggers and error messages are displayed:

This is just what we want. If we go back to the name field and try to enter just a single character before tabbing away, the minimum length validation error triggers, as we would expect:

Our generic form component is nearly complete now. Our final task is to submit the form, which we'll do in the next section.

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

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