Jamescun Legit Save

input validation framework

Project README
LEGIT

GoDoc

Legit is an input validation framework for Go. Legit differs from existing frameworks by constructing validation from types and interfaces, preferring custom validators to complex struct tags.

go get -u github.com/jamescun/legit

Included validators:

  • Email
  • UUID
  • UUID3
  • UUID4
  • UUID5
  • Credit Card
  • Lowercase
  • Uppercase
  • No whitespace
  • Printable characters
  • Alpha
  • Alphanumeric
  • Numeric
  • ASCII
  • Positive number
  • Negative number

Example

package main

import (
	"fmt"
	"net/http"

	"github.com/jamescun/legit"
)

type User struct {
	Email legit.Email    `json:"email"`
	Age   legit.Positive `json:"age"`
}

func Handler(w http.ResponseWriter, r *http.Request) {
	var user User
	err := legit.ParseRequestAndValidate(r, &user)
	if err != nil {
		fmt.Fprintln(w, "invalid user:", err)
		return
	}
}

Custom Example

package main

import (
	"fmt"
	"regexp"
	"errors"
	"encoding/json"

	"github.com/jamescun/legit"
)

type Name string

// very simplistic regexp for human name validation
var expName = regexp.MustCompile(`[a-zA-Z\ ]{1,64}`)

// attach Validate() method to our custom name type, satisfying the legit.Object interface,
// defining our custom name validation.
func (n Name) Validate() error {
	if !expName.MatchString(string(n)) {
		return errors.New("invalid name")
	}

	return nil
}

type User struct {
	Email legit.Email `json:"email"`
	Name  Name        `json:"name"`
}

func main() {
	body := []byte(`{"email": "[email protected]", "name": "John Doe"}`)
	
	var user User
	json.Unmarshal(body, &user)

	err := legit.Validate(user)
	if err != nil {
		fmt.Println("invalid user!", err)
	}
}

Open Source Agenda is not affiliated with "Jamescun Legit" Project. README Source: jamescun/legit
Stars
81
Open Issues
0
Last Commit
6 years ago
Repository
License

Open Source Agenda Badge

Open Source Agenda Rating