go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.07k stars 1.29k forks source link

Alpha Space #1191

Open shamir92 opened 8 months ago

shamir92 commented 8 months ago

Package version eg. v9, v10: v10

Issue, Question or Enhancement:

Alpha validator cannot have space. I think we need it.

Code sample, to showcase or reproduce:


    hasPass := regexp.MustCompile(`^[a-zA-Z ]+$`).MatchString(reqData.Name)
trungdlp-wolffun commented 5 months ago

I custom validator @shamir92

var regexAlphaNumSpace = regexp.MustCompile("^[ \\p{L}\\p{N}]+$")

var Ins   *validator.Validate

func init() {
  Ins = validator.New()
  Ins.RegisterValidation("alphanumspace", ValidateAlphaNumSpace)
}

func ValidateAlphaNumSpace(fl validator.FieldLevel) bool {
  return regexAlphaNumSpace.MatchString(fl.Field().String())
}

Use:

type Request struct {
  Name string `json:"name" validate:"required,alphanumspace"`
}
zemzale commented 5 months ago

Changing the current validator would be a breaking change.

But I can see benefit for such a validator so feel free to open a PR for that

nic6200 commented 5 months ago

Hi @zemzale. Can I add a new validation for alpha spaces?

krobitaille-stash commented 2 months ago

Would love this but I think the regex should be modified so only whitespace isn't valid?