React Gin Blog (6/19): Form validations

As we saw in previous section, our handlers are working as expected when we pass valid data. But what about not valid data? Or missing data? Let’s test this. First, let’s remove (or just comment) Password: passwordValue from our submitHandler() inside of assets/src/components/Auth/AuthForm.js. This way, our backend will send only Username, without Password. Let’s now create new account again. We can see in browser dev tools that only Username is sent, but request returned status OK, we got JWT and user is created without password. Of course, we don’t want that. That’s why we need to add form validations.

Fortunately, adding validations is easy. Inside of internal/store/users.go where User struct is defined, just add these tags:

type User struct {
  Username string `binding:"required,min=5,max=30"`
  Password string `binding:"required,min=7,max=32"`

This tells Gin what fields are required, as well what minimum and maximum allowed lengths are. Gin uses go-playground/validator, so all supported validators and tags can be found here.

If we try to sign up or sign in again using modified version of AuthForm without sending Password field, we will get error.

Form validations

Now we can revert AuthForm.js to original state to send Password field again, and everything should work. You can also try to sign up or sign in with too short or too long username/password to verify that min and max validations are also working as expected.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: