Skip to content

Instantly share code, notes, and snippets.

@alphaqiu
Forked from fearblackcat/checkpasword.md
Created July 10, 2018 08:47
Show Gist options
  • Save alphaqiu/c9f04bbefec8f6b01c6dbbb028e8ad29 to your computer and use it in GitHub Desktop.
Save alphaqiu/c9f04bbefec8f6b01c6dbbb028e8ad29 to your computer and use it in GitHub Desktop.
password check in golang
package main

import (
        "fmt"
        "unicode"
)

func validPassword(s string) error {
next:
        for name, classes := range map[string][]*unicode.RangeTable{
                "upper case": {unicode.Upper, unicode.Title},
                "lower case": {unicode.Lower},
                "numeric":    {unicode.Number, unicode.Digit},
                "special":    {unicode.Space, unicode.Symbol, unicode.Punct, unicode.Mark},
        } {
                for _, r := range s {
                        if unicode.IsOneOf(classes, r) {
                                continue next
                        }
                }
                return fmt.Errorf("password must have at least one %s character", name)
        }
        return nil
}

func main() {
        for _, s := range []string{
                "bad",
                "testPassword",
                "testPa##word",
                "b3tterPa$$w0rd",
        } {
                fmt.Printf("validPassword(%q) = %v\n", s, validPassword(s))
        }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment