DEV Community

Matija Krajnik
Matija Krajnik

Posted on • Updated on • Originally published at letscode.blog

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.

Without 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"`
}
Enter fullscreen mode Exit fullscreen mode

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.

With 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.

Oldest comments (0)