Forms 0 exercises
lesson

Client-Side Form Validation

Adding the remaining first and last name fields to the form is a similar process to adding the email field. Copying and pasting the email field and modifying the name and description will do the trick:


// inside RegistrationForm.tsx
return (
<Form {...form}>
<form
classNa

Loading lesson

Transcript

00:00 All right, let's go take a look at the code and we'll go and add in our first and last name fields. To do that, I'll bring in two additional form fields and either basically just copy and paste of the original email field where I just changed the name of the field and also the description. Let's take a look.

00:16 It looks nice, but I do want first and last name set side by side, so I'm going to add a little bit more tailwind. I'm just going to wrap this form field in a div that has a flex box that's going to go in by default, put them side by side with a little gap in the middle. Magnifique.

00:36 But does it validate? Let's give it a try. If I hit submit here, nothing happens. So what's going on? Well, what's happening is that we actually haven't connected the handle submit to the actual on submit, which is triggered when you click on submit here.

00:52 So let's go and create an on submit and then connect it to our form. So I'll create a new on submit function right at the top here. And what's going to be passed to on submit is again, the type of our schema. So we're going to use that Z infer trick again to get the type of our schema. And that means that we don't actually have to synchronize any of this.

01:10 Anytime we change the schema, basically all of this is going to change automatically for us, which is fantastic. Now, at this point, all it's going to do is just console log out the data that comes in. So now we just have to connect it to the form. Do that down in the form field. We add an on submit prop. We first pass the on submit to handle submit.

01:30 That's going to wrap it so that all of those validations are applied. So let's hit save and say we go, all right, let's just keep it empty, hit submit and everything's invalid. That's fantastic. Let's see in the console. Did I get anything? Nope. All right, let's go. Okay. Hit submit.

01:49 And now I get on submit called with all the data and everything's been trimmed and validated. Fantastic. So now we've got client side validation working and wow, that was super easy, right? Let's actually post this to the server and see how to go and validate it on the server