Implementing validation on the ask and answer forms

We are going to implement validation in both the ask and answer forms now in the following steps:

  1. In AskPage.tsx, we are going to make sure that the title and content fields are populated by the user with a minimum number of characters. First, let's import the required and minLength validators:
import { Form, required, minLength } from './Form';
  1. Now, we can add the validation rules to the Form component in the AskPage component JSX:
<Form
submitCaption="Submit Your Question"
validationRules={{
title: [
{ validator: required },
{ validator: minLength, arg: 10 },
],
content: [
{ validator: required },
{ validator: minLength, arg: 50 },
],
}}

>
...
</Form>
  1. Let's give this a try. In the running app, let's go to the ask page by clicking on the Ask a question button on the home screen. 
  2. If we tab through the title without filling it in and then enter content that is less than 50 characters, we'll see the validation errors rendered:

We can still press the submit button because we haven't implemented any logic to disable the submit button if there are any validation errors.

  1. Let's move onto the answer form now in QuestionPage.tsx. We are going to validate that the content is filled in with at least 50 characters. Let's import the required and minLength validators:
import { Form, required, minLength } from './Form';
  1. In the QuestionPage component JSX, let's add the validation rules to the Form component:
<Form
submitCaption='Submit Your Answer'
validationRules={{
content: [
{ validator: required },
{ validator: minLength, arg: 50 }
]
}}
>
<Field name="content" label="Your Answer" type="TextArea" />
</Form>
  1. In the running app, we can check that this is working as we expect by clicking on a question on the home page and entering an answer:

That completes the implementation of validation on our forms. 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
18.223.133.169