DEV Community

Matija Krajnik
Matija Krajnik

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

3 2

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay