0

I need to add special characters (@#$%^&.?) to the oneof or use regexp, but regexp errors on execution is undefined. I am currently using, oneof=uppercase&lowercase&numeric. this validator would be checking if the passwords contain at least 1 uppercase letter, 1 lowercase letter, 1 number and 1 special character.

Sample Code ==>

package main

import (
    "fmt"

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

type UserReg struct {
    Username        string `validate:"required,min=4,max=15"`
    Email           string `validate:"required,email"`
    Password        string `validate:"required,min=8,max=20,eqfield=ConfirmPassword,oneof=uppercase&lowercase&numeric"`
    ConfirmPassword string `validate:"required,min=8,max=20,oneof=uppercase&lowercase&numeric"`
}

type UserReg2 struct {
    Username        string `validate:"required,min=4,max=15"`
    Email           string `validate:"required,email"`
    Password        string `validate:"required,min=8,max=20,eqfield=ConfirmPassword,regexp=^(?=.*[a-zA-Z0-9!@#$%^&.?/]).$"`
    ConfirmPassword string `validate:"required,min=8,max=20,regexp=^(?=.*[a-zA-Z0-9!@#$%^&.?/]).$"`
}

func main() {

    fmt.Println("Start of working test w/o check for special characters")

    ut := UserReg{
        Username:        "Joe23",
        Email:           "[email protected]",
        Password:        "Pa55w0rd",
        ConfirmPassword: "Pa55w0rd",
    }

    validate := validator.New()

    err := validate.Struct(ut)
    fmt.Println(err)

    fmt.Println("End of working test w/o check for special characters")

    fmt.Println("Start of failing test w/ check for special characters")

    ut2 := UserReg2{
        Username:        "Joe23",
        Email:           "[email protected]",
        Password:        "Pa$$w0rd",
        ConfirmPassword: "Pa$$w0rd",
    }

    err2 := validate.Struct(ut2)
    fmt.Println(err2)

    fmt.Println("End of failing test w/ check for special characters")
}
2
  • 1
    Please post a stackoverflow.com/help/minimal-reproducible-example Commented Dec 23, 2022 at 17:50
  • 1
    Changed original post deleting the code that was there and replacing it with a full example program Commented Dec 23, 2022 at 20:14

1 Answer 1

2

After playing around I came up with by changing the line in UserReg to:

    Password        string `validate:"required,min=8,max=20,eqfield=ConfirmPassword,oneof=uppercase&lowercase&numeric&@ # $ % ^ \& . ? \/"`
    ConfirmPassword string `validate:"required,min=8,max=20,oneof=uppercase&lowercase&numeric&@ # $ % ^ \& . ? \/"`
Sign up to request clarification or add additional context in comments.

1 Comment

In the future, you can use something like regex101.com to test your regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.