Skip to content

Commit

Permalink
bugfix: validation error while registering (#85)
Browse files Browse the repository at this point in the history
bugfix: validation error while registering
  • Loading branch information
masnann authored Dec 5, 2023
2 parents 6f7d34c + 40d85d0 commit 6a35674
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
8 changes: 4 additions & 4 deletions module/feature/auth/dto/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package dto

type RegisterRequest struct {
Email string `form:"email" json:"email" validate:"required,email"`
Password string `form:"password" json:"password" validate:"required,min=6"`
Password string `form:"password" json:"password" validate:"required,min=6,noSpace"`
}

type LoginRequest struct {
Email string `form:"email" json:"email" validate:"required,email"`
Password string `form:"password" json:"password" validate:"required,min=6"`
Password string `form:"password" json:"password" validate:"required,min=6,noSpace"`
}

type EmailRequest struct {
Expand All @@ -24,6 +24,6 @@ type ForgotPasswordRequest struct {
}

type ResetPasswordRequest struct {
NewPassword string `json:"new_password" validate:"required,min=6"`
ConfirmPassword string `json:"confirm_password" validate:"required,min=6"`
NewPassword string `json:"new_password" validate:"required,min=6,noSpace"`
ConfirmPassword string `json:"confirm_password" validate:"required,min=6,noSpace"`
}
37 changes: 35 additions & 2 deletions utils/validate.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,46 @@
package utils

import "github.com/go-playground/validator/v10"
import (
"errors"
"fmt"
"strings"

"github.com/go-playground/validator/v10"
)

var validate *validator.Validate

func init() {
validate = validator.New()
_ = validate.RegisterValidation("noSpace", noSpace)
}

func noSpace(fl validator.FieldLevel) bool {
password := fl.Field().String()
return !strings.Contains(password, " ")
}

func ValidateStruct(s interface{}) error {
return validate.Struct(s)
err := validate.Struct(s)
if err != nil {
var customErrors []string

for _, err := range err.(validator.ValidationErrors) {
switch err.Tag() {
case "required":
customErrors = append(customErrors, fmt.Sprintf("Field '%s' wajib diisi", err.Field()))
case "min":
customErrors = append(customErrors, fmt.Sprintf("Field '%s' minimal harus memiliki panjang %s karakter", err.Field(), err.Param()))
case "email":
customErrors = append(customErrors, fmt.Sprintf("Field '%s' harus berupa alamat email yang valid", err.Field()))
case "noSpace":
customErrors = append(customErrors, fmt.Sprintf("Field '%s' tidak boleh mengandung spasi", err.Field()))
default:
customErrors = append(customErrors, fmt.Sprintf("Validasi field '%s' gagal dengan tag '%s'", err.Field(), err.Tag()))
}
}

return errors.New(strings.Join(customErrors, "; "))
}
return nil
}

0 comments on commit 6a35674

Please sign in to comment.