funcvalid

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2023 License: MIT Imports: 7 Imported by: 0

README

funcvalid

Validator in functional style

This package provides a functional style API to validating data. It's type safe, meaning that a lot of possible errors are already detected at compile time, not runtime. The basic idea is that validators for any datatype are just functions that return an error or nil. Parametrized validators can be constructed by a functional technic called curried functions. It's easy to create is-validators by uncurrying exisiting validators. It's easy to construct new validator functions from the existing ones, by using special validators that combine other validators, that's the approach to build validators for your complex types (e.g. structs, maps).

Installation

Use:

go get github.com/krizmak/funcvalid

Then import it into your code:

import (fv "github.com/krizmak/funcvalid")

Acknowledment

The package uses some files from the tag based validator package: https://github.com/go-playground/validator based on the kind permission of the author https://github.com/deankarn.

Similar packages

Just after I had started working on this package, I found https://github.com/go-ozzo/ozzo-validation, that provides similar approach (type-safe validation). However the functional style API is unique to this package, and my have benefit for others, who like this style.

How to Contribute

Make a pull request.

License

See https://github.com/krizmak/funcvalid/blob/main/LICENSE (MIT license)

Maintainers

The package is in an early phase, maintined only by the author https://github.com/krizmak. Any help is appreciated.

Documentation

Overview

Package funcvalid is a tiny validator package in functional style.

Unlike the usual go validators, it does not rely on the tag feature of the structs, because they don't benefit from the type safety that golang types ensures.

So funcvalid package:

  • provides a type-safe validation framework
  • in a relatively dense format.

The main concept is that a validator is simply a function that takes an input and returns an error if the validation is unsuccessful or nil, if it is successful.

  // Define the validator function type for ints
  type IntValidator func(input int) error

	// Here we create a validator function for ints (i.e. its type is IntValidator)
	func IntEq42(input int) error {
		if (input == 42) {
			return nil
		}
		return errors.New(fmt.Sprintf("Input %d doesn't answer to life the universe and everything.")
	}

	// Now we can use the validator this way:
	IntEq42(42)  // -> nil
	IntEq42(0)   // -> error

It doesn't seem very useful until now, because in most of the cases the validators need a parameter, too.

This package provides factory functions, that may take arguments and return a validator. It works a bit like currying in functional languages hence the name. The idea comes from this excellent curry post.

If it still sounds a bit cryptic, let's see the following example:

// We create a general validator generator (factory function) that takes a parameter, and it will return
// the actual validator function:
func IntEq(pattern int) IntValidator {
	// Here we create the validator function (i.e. its type is IntValidator)
	// as it's a closure, it can use the pattern parameter, too.
	return func(input int) error {
		if (input == pattern) {
			return nil
		}
		return errors.New(fmt.Sprintf("Input %d doesn't answer to life the universe and everything.")
	}
}

// Now the usage is like:
IntEq(42)(42)  // -> nil
IntEq(42)(0)   // -> error

The actual factory functions are even a bit more generak by using generic types. The package also provides Not, Or and And factory functions with that you can chain other validators.

For further details see the documentation of the functions, and have a functional fun in Go!

I've copied/reworked most of the built-in validators from the validator package, that is the best of the tag based validators.

Factory functions composed from Regexp factory function and regexp collection from https://github.com/go-playground/validator

Index

Constants

This section is empty.

Variables

View Source
var (
	Alpha                 = RegexpRE(alphaRegex)
	AlphaNumeric          = RegexpRE(alphaNumericRegex)
	AlphaUnicode          = RegexpRE(alphaUnicodeRegex)
	AlphaUnicodeNumeric   = RegexpRE(alphaUnicodeNumericRegex)
	Numeric               = RegexpRE(numericRegex)
	Number                = RegexpRE(numberRegex)
	Hexadecimal           = RegexpRE(hexadecimalRegex)
	HexColor              = RegexpRE(hexColorRegex)
	Rgb                   = RegexpRE(rgbRegex)
	Rgba                  = RegexpRE(rgbaRegex)
	Hsl                   = RegexpRE(hslRegex)
	Hsla                  = RegexpRE(hslaRegex)
	E164                  = RegexpRE(e164Regex)
	Email                 = RegexpRE(emailRegex)
	Base64                = RegexpRE(base64Regex)
	Base64URL             = RegexpRE(base64URLRegex)
	Base64RawURL          = RegexpRE(base64RawURLRegex)
	ISBN10                = RegexpRE(iSBN10Regex)
	ISBN13                = RegexpRE(iSBN13Regex)
	UUID3                 = RegexpRE(uUID3Regex)
	UUID4                 = RegexpRE(uUID4Regex)
	UUID5                 = RegexpRE(uUID5Regex)
	UUID                  = RegexpRE(uUIDRegex)
	UUID3RFC4122          = RegexpRE(uUID3RFC4122Regex)
	UUID4RFC4122          = RegexpRE(uUID4RFC4122Regex)
	UUID5RFC4122          = RegexpRE(uUID5RFC4122Regex)
	UUIDRFC4122           = RegexpRE(uUIDRFC4122Regex)
	ULID                  = RegexpRE(uLIDRegex)
	Md4                   = RegexpRE(md4Regex)
	Md5                   = RegexpRE(md5Regex)
	Sha256                = RegexpRE(sha256Regex)
	Sha384                = RegexpRE(sha384Regex)
	Sha512                = RegexpRE(sha512Regex)
	Ripemd128             = RegexpRE(ripemd128Regex)
	Ripemd160             = RegexpRE(ripemd160Regex)
	Tiger128              = RegexpRE(tiger128Regex)
	Tiger160              = RegexpRE(tiger160Regex)
	Tiger192              = RegexpRE(tiger192Regex)
	ASCII                 = RegexpRE(aSCIIRegex)
	PrintableASCII        = RegexpRE(printableASCIIRegex)
	Multibyte             = RegexpRE(multibyteRegex)
	DataURI               = RegexpRE(dataURIRegex)
	Latitude              = RegexpRE(latitudeRegex)
	Longitude             = RegexpRE(longitudeRegex)
	SSN                   = RegexpRE(sSNRegex)
	HostnameRFC952        = RegexpRE(hostnameRegexRFC952)
	HostnameRFC1123       = RegexpRE(hostnameRegexRFC1123)
	FqdnRFC1123           = RegexpRE(fqdnRegexRFC1123)
	BtcAddress            = RegexpRE(btcAddressRegex)
	BtcUpperAddressBech32 = RegexpRE(btcUpperAddressRegexBech32)
	BtcLowerAddressBech32 = RegexpRE(btcLowerAddressRegexBech32)
	EthAddress            = RegexpRE(ethAddressRegex)
	URLEncoded            = RegexpRE(uRLEncodedRegex)
	HTMLEncoded           = RegexpRE(hTMLEncodedRegex)
	HTML                  = RegexpRE(hTMLRegex)
	JWT                   = RegexpRE(jWTRegex)
	SplitParams           = RegexpRE(splitParamsRegex)
	Bic                   = RegexpRE(bicRegex)
	Semver                = RegexpRE(semverRegex)
	DnsRFC1035Label       = RegexpRE(dnsRegexRFC1035Label)
	Cve                   = RegexpRE(cveRegex)
	Mongodb               = RegexpRE(mongodbRegex)
	Cron                  = RegexpRE(cronRegex)
	SpicedbID             = RegexpRE(spicedbIDRegex)
	SpicedbPermission     = RegexpRE(spicedbPermissionRegex)
	SpicedbType           = RegexpRE(spicedbTypeRegex)
)
View Source
var (
	Iso3166Alpha2       = KeyIn(iso3166_1_alpha2)
	Iso3166Alpha3       = KeyIn(iso3166_1_alpha3)
	Iso3166AlphaNumeric = KeyIn(iso3166_1_alpha_numeric)
	Iso4217             = KeyIn(iso4217)
	Iso4217Numeric      = KeyIn(iso4217_numeric)
	PostCodeByIso3166   = func(country_code string) Validator[string] {
		if _, ok := postCodePatternDict[country_code]; !ok {
			return ErrorValidator[string]("invalid country code")
		}
		return Regexp(postCodePatternDict[country_code])
	}
)

Functions

func AnyErr

func AnyErr(errs ...error) error

Helper function that takes variable number of errors or nils, and returns an err if any of the params is not nil.

func File added in v0.2.0

func File(input string) error

File is the validation function for validating if the input is a valid existing file path.

func HttpUrl added in v0.2.0

func HttpUrl(input string) error

func URI added in v0.2.0

func URI(input string) error

func Url added in v0.2.0

func Url(input string) error

func UrnRFC2141 added in v0.2.0

func UrnRFC2141(input string) error

UrnRFC2141 is the validation function for validating if the input is a valid URN as per RFC 2141.

Types

type Validable

type Validable interface {
	// contains filtered or unexported methods
}

Interface with a single function that validates the type. A simple example struc that implements the Validable interface:

   type LoginReqData struct {
	      Username string
	      Password string
     }

   func (l LoginReqData) validate() error {
   	return fv.AnyErr(
		      fv.LenBw[string](1, 30)(l.Username), //Username length should be between 1 and 30
		      fv.LenBw[string](7, 32)(l.Password)) //Password length should be between 7 and 32
   }

type Validator

type Validator[T any] func(inp T) error

The generic validator function type.

func And

func And[T any](validators ...Validator[T]) Validator[T]

Factory function that takes variable number of validators, and returns a validator that validates if all the parameter validators are valid.

func Eq

func Eq[T comparable](pattern T) Validator[T]

Factory function with a paramter that returns a validator, that validates if the input value equals to the parameter.

func ErrorValidator added in v0.2.0

func ErrorValidator[T any](error_msg string) Validator[T]

Factory function with a string parameter that returns a validator, that always return error with the message in the parameter.

func Gt added in v0.1.0

func Gt[T constraints.Ordered](pattern T) Validator[T]

Factory function with a parameter that returns a validator, that validates if the input value less than the parameter.

func KeyIn added in v0.2.0

func KeyIn[K comparable, V any](validmap map[K]V) Validator[K]

Factory function with a map parameter that returns a validator, that validates if the input is one of the keys in the map.

func LenBw

func LenBw[T string | []T](min int, max int) Validator[T]

Factory function with two parameters that returns a validator, that validates if the length of the input array or string is between the two parameters.

func LenEq

func LenEq[T string | []T](length int) Validator[T]

Factory function with a parameter that returns a validator, that validates if the length of the input array or string equals to the parameter.

func LenGt

func LenGt[T string | []T](length int) Validator[T]

Factory function with a parameter that returns a validator, that validates if the length of the input array or string greater than the parameter.

func LenLt

func LenLt[T string | []T](length int) Validator[T]

Factory function with a parameter that returns a validator, that validates if the length of the input array or string less than the parameter.

func Lt

func Lt[T constraints.Ordered](pattern T) Validator[T]

Factory function with a parameter that returns a validator, that validates if the input value less than the parameter.

func Not added in v0.1.0

func Not[T any](validator Validator[T]) Validator[T]

Factory function that takes variable number of validators, and returns a validator that validates if all the parameter validators are valid.

func OneOf added in v0.1.0

func OneOf[T comparable](elems ...T) Validator[T]

Factory function with a number of parameters that returns a validator, that validates if the input is one of the values in the parameters.

func Or

func Or[T any](validators ...Validator[T]) Validator[T]

Factory function that takes variable number of validators, and returns a validator that validates if any of the parameter validators are valid.

func Regexp

func Regexp(pattern string) Validator[string]

Factory function with a regexp string parameter that returns a validator, that validates if the input value matches to the regexp.

func RegexpRE added in v0.2.0

func RegexpRE(pattern *regexp.Regexp) Validator[string]

Factory function with a regexp parameter that returns a validator, that validates if the input value matches to the regexp.

func ValueIn added in v0.2.0

func ValueIn[K comparable, V comparable](validmap map[K]V) Validator[V]

Factory function with a map parameter that returns a validator, that validates if the input is one of the values in the map.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL