Build and Validate a Form in Vanilla React

Share this video with your friends

Social Share Links

Send Tweet

Learn how to make forms and validate form fields using the onBlur event without any external React helper library/component.

With this knowledge, you will understand what problem the next lesson is trying to solve.

Instructor: [00:00] Let's start with a simple user form, which has a single field. The field is made of a label for user name and input for receiving the username. The input also needs to have a value prop, which you can pass a state item to.

[00:32] Let's go ahead and create the state. Then, add a button that would submit the form. We need to make the input a controlled element for adding on a change handler. We can name the function handleUserNameChange.

[00:59] Then we can implement this handler. Basically, what we need to do here is to update this state whenever the value changes. We can do this.setState, user name, and then the new value coming from the event object, a value.

[01:23] We can pass in the event object, the function. We can also add a simple validation using the onBelow event, user name below. Then we can implement this function as well.

[01:45] What we need to do here is, if the value doesn't exist, then we can set the state of an errors object. An errors object that has a user name field, so user name is required. If that's not the case, then we can just do the same thing, but leave the value empty.

[02:35] We also need to go ahead and create the errors object and the user name field. I think I misspelled the onBelow event. [laughs] It should be onBelow, not onBelew. We can simply show the error message in a paragraph.

[03:00] We can change the color of the text to red, just to show that some error. You can ead to the output, click an input, and click outside to get the user name of a validation error, since the field is empty. Once you start typing out and click out once more, the validation error disappears.

[03:25] The last thing that we need to do is to add an onSubmit handler to the form, handleSubmit. Then we can create the handleSubmit method, which receives the event object as well, and just basically logs out the value of the state.

[03:56] If you pull up the console, fill out the form, submit, we should see the user name value and the errors object.