-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
bugfix: validation error while registering (#85)
bugfix: validation error while registering
- Loading branch information
Showing
2 changed files
with
39 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |