In this lesson, we'll see how to do form validations in the browser using React.
It’s important to do validations on the server before saving user-submitted data but there are some things we can do on the client to stop the user from submitting invalid data.
This saves the user time and makes for a better user experience.
In the previous lesson, we added a constraint on the appointment title - it needs to be at least 3 characters long. But we only check if the value entered by the user passes this validation once they submit the form. So it takes a round trip to the server to tell the user that there’s a problem with the data.
We can easily check for this in the client with React and give the user real-time feedback about validation.
We can disable the form submit button unless the form field values are valid.
Let’s do that with the title field first.
In our AppointmentForm component, let’s set the disabled attribute of the form submit button to a prop that we’ll pass to it.
Now, we need to watch for the user input in the title field and update the state value formValid based on the length of the input.
We already have the handleUserInput function which updates the state with the value of the input.
handleUserInput (obj) {
this.setState(obj);
}
So let’s modify that to also trigger a validation.
The setState function accepts a second optional argument which is a callback function that’s executed once setState is completed and the component is re-rendered.
So we can pass a validation function as the second optional argument to setState. Let's call it validateForm.