Validation

Learn how to validate user input in your Caesar web app.

Overview

In a Caesar web app, the recommended way to validate user inputs is to use the validator package. The validator package is a powerful package that provides a simple way to validate data by using tags in your structs.

Caesar provides a simple method on the CaesarCtx, Validate, that you can use to validate user inputs.

Using the validator package

  1. First, define a struct that represents the data you want to validate.
// ./app/controllers/sign_up_controller.go

// ...

// For example, let's define a struct for sign up data.
// 
// See https://github.com/go-playground/validator 
// for more information on the validator package.
type SignUpValidator struct {
	Email    string `form:"email" validate:"required,email"`
	FullName string `form:"full_name" validate:"required,min=3"`
	Password string `form:"password" validate:"required,min=8"`
}
  1. Next, use the Validate method on the CaesarCtx to validate the user input.
// ./app/controllers/sign_up_controller.go

// ...

func (c *SignUpController) Handle(ctx *caesar.CaesarCtx) error {
	data, errors, ok := caesar.Validate[SignUpValidator](ctx)
	if !ok {
		return ctx.Render(authPages.SignUpForm(
			authPages.SignUpInput{Email: data.Email, FullName: data.FullName, Password: data.Password},
			errors,
		))
	}

    // ...
}

In the example above, we use the Validate method to validate the user input against the SignUpValidator struct.

If the validation fails, we render the sign-up form with the input data and the validation errors, so the user can see what went wrong.

The returned errors variable is a map of field names to error messages (map[string]string). You can use this map to display error messages to the user.

  1. Show the validation errors in the view.
// ./views/pages/auth/sign_up.templ

// ...

templ SignUpForm(input SignUpInput, errors map[string]string) {
	<form class="space-y-4 mt-6" hx-post="/auth/sign_up">
		@ui.InputField(ui.InputFieldProps{
			Label:       "Full Name",
			Type:        "text",
			Id:          "full_name",
			Placeholder: "John Doe",
			Required:    true,
			Value:       input.FullName,
			Error:       errors["FullName"],
		}) 
        // ...
    </form>
}