Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSN regex doesn't match the rest of the validation and is loose with formatting rules #1272

Open
2 tasks done
nderscore opened this issue May 29, 2024 · 0 comments
Open
2 tasks done

Comments

@nderscore
Copy link

  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

The ssn validation is composed of two checks:

  1. A length check on the input string, checking for 11 characters.

if field.Len() != 11 {

  1. A regular expression to check the pattern of that string

sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$`

The regular expression includes this optional (0 or 1) character class [ -]? as the separator between each segment of the social security number, meaning it supports each of the following formats:

  • 123-12-1234
  • 123 12 1234
  • 123-12 1234
  • 123 12-1234
  • 123 121234
  • 12312 1234
  • 12312-1234
  • 123-121234
  • 123121234

This presents at least two issues:

  1. The length check means that social security numbers with formatting stripped (123121234) will not pass the validation, despite the regular expression matching it. Since it's pretty common to deal with unformatted values, it might be worth supporting strings with a length of 9 in addition to 11

  2. The regular expression is a bit too loose with formatting. Mixed usage of spaces and hyphens is not something that I would expect to pass the validation. The regular expression should probably enforce consistent separators.

Code sample, to showcase or reproduce:

package main

import (
	"fmt"

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

type Foo struct {
	Ssn string `validate:"ssn"`
}

var validate *validator.Validate

func main() {
	validate = validator.New(validator.WithRequiredStructEnabled())

	cases := []string{
		"123-12-1234",
		"123 12 1234",
		"123-12 1234",
		"123 12-1234",
		"123 121234",
		"12312 1234",
		"12312-1234",
		"123-121234",
		"123121234",
	}

	for _, s := range cases {
		ss := Foo{Ssn: s}
		err := validate.Struct(ss)
		fmt.Printf("%s = +%v\n", s, err)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant