Aşağıdaki örneği kullanarak kullanıcı şifresinin beklentileri karşılayıp karşılamadığını kontrol edebilirsiniz.


Doğrulayıcı


package validator

import (
"unicode"
)

// Password validates plain password against the rules defined below.
//
// upp: at least one upper case letter.
// low: at least one lower case letter.
// num: at least one digit.
// sym: at least one special character.
// tot: at least eight characters long.
// No empty string or whitespace.
func Password(pass string) bool {
var (
upp, low, num, sym bool
tot uint8
)

for _, char := range pass {
switch {
case unicode.IsUpper(char):
upp = true
tot++
case unicode.IsLower(char):
low = true
tot++
case unicode.IsNumber(char):
num = true
tot++
case unicode.IsPunct(char) || unicode.IsSymbol(char):
sym = true
tot++
default:
return false
}
}

if !upp || !low || !num || !sym || tot < 8 {
return false
}

return true
}

Test


package validator

import (
"testing"
)

func TestPassword(t *testing.T) {
tests := []struct {
name string
pass string
valid bool
}{
{
"NoCharacterAtAll",
"",
false,
},
{
"JustEmptyStringAndWhitespace",
" \n\t\r\v\f ",
false,
},
{
"MixtureOfEmptyStringAndWhitespace",
"U u\n1\t?\r1\v2\f34",
false,
},
{
"MissingUpperCaseString",
"uu1?1234",
false,
},
{
"MissingLowerCaseString",
"UU1?1234",
false,
},
{
"MissingNumber",
"Uua?aaaa",
false,
},
{
"MissingSymbol",
"Uu101234",
false,
},
{
"LessThanRequiredMinimumLength",
"Uu1?123",
false,
},
{
"ValidPassword",
"Uu1?1234",
true,
},
}

for _, c := range tests {
t.Run(c.name, func(t *testing.T) {
if c.valid != Password(c.pass) {
t.Fatal("invalid password")
}
})
}
}

=== RUN   TestPassword
=== RUN TestPassword/NoCharacterAtAll
=== RUN TestPassword/JustEmptyStringAndWhitespace
=== RUN TestPassword/MixtureOfEmptyStringAndWhitespace
=== RUN TestPassword/MissingUpperCaseString
=== RUN TestPassword/MissingLowerCaseString
=== RUN TestPassword/MissingNumber
=== RUN TestPassword/MissingSymbol
=== RUN TestPassword/LessThanRequiredMinimumLength
=== RUN TestPassword/ValidPassword
--- PASS: TestPassword (0.00s)
--- PASS: TestPassword/NoCharacterAtAll (0.00s)
--- PASS: TestPassword/JustEmptyStringAndWhitespace (0.00s)
--- PASS: TestPassword/MixtureOfEmptyStringAndWhitespace (0.00s)
--- PASS: TestPassword/MissingUpperCaseString (0.00s)
--- PASS: TestPassword/MissingLowerCaseString (0.00s)
--- PASS: TestPassword/MissingNumber (0.00s)
--- PASS: TestPassword/MissingSymbol (0.00s)
--- PASS: TestPassword/LessThanRequiredMinimumLength (0.00s)
--- PASS: TestPassword/ValidPassword (0.00s)
PASS
ok internal/pkg/validator 0.010s