Documentation
¶
Overview ¶
Package validate (go-validate) provides validations for struct fields based on a validation tag and offers additional validation functions.
Index ¶
- Variables
- func AddValidation(key string, fn func(string, reflect.Kind) (Interface, error))
- func IsValidDNSName(dnsName string) bool
- func IsValidEmail(email string, mxCheck bool) (success bool, err error)
- func IsValidEnum(enum string, allowedValues *[]string, emptyValueAllowed bool) (success bool, err error)
- func IsValidHost(host string) bool
- func IsValidIP(ipAddress string) bool
- func IsValidIPv4(ipAddress string) bool
- func IsValidIPv6(ipAddress string) bool
- func IsValidPhoneNumber(phone string, countryCode string) (success bool, err error)
- func IsValidSocial(social string) (success bool, err error)
- type Interface
- type Map
- type Validation
- type ValidationError
- type ValidationErrors
Examples ¶
- IsValid (CompareString)
- IsValid (FormatEmail)
- IsValid (FormatRegEx)
- IsValid (MaxFloat)
- IsValid (MaxInt)
- IsValid (MaxLength)
- IsValid (MinFloat)
- IsValid (MinInt)
- IsValid (MinLength)
- IsValidDNSName (Invalid)
- IsValidDNSName (Valid)
- IsValidEmail (Invalid)
- IsValidEmail (Valid)
- IsValidEnum (Invalid)
- IsValidEnum (Valid)
- IsValidHost (Invalid)
- IsValidHost (Valid)
- IsValidIP (Invalid)
- IsValidIP (Valid)
- IsValidPhoneNumber (Invalid)
- IsValidPhoneNumber (Valid)
- IsValidSocial (Invalid)
- IsValidSocial (Valid)
- ValidationError.Error
Constants ¶
This section is empty.
Variables ¶
var DefaultMap = Map{}
DefaultMap is the default validation map used to tell if a struct is valid.
Functions ¶
func AddValidation ¶
AddValidation registers the validation specified by a key to the known validations. If more than one validation registers with the same key, the last one will become the validation for that key using DefaultMap.
func IsValidDNSName ¶ added in v0.1.7
IsValidDNSName will validate the given string as a DNS name
Example (Invalid) ¶
ExampleIsValidDNSName_invalid example of an invalid dns name
ok := IsValidDNSName("localhost.-localdomain") fmt.Println(ok)
Output: false
Example (Valid) ¶
ExampleIsValidDNSName_valid example of a valid dns name
ok := IsValidDNSName("localhost") fmt.Println(ok)
Output: true
func IsValidEmail ¶ added in v0.1.1
IsValidEmail validate an email address using regex, checking name and host, and even MX record check
Example (Invalid) ¶
ExampleIsValidEmail_invalid example of an invalid email address response
ok, err := IsValidEmail("notvalid@domain", false) // Invalid fmt.Println(ok, err)
Output: false email is not a valid address format
Example (Valid) ¶
ExampleIsValidEmail_valid example of a valid email address response
ok, err := IsValidEmail("person@gmail.com", false) // Valid fmt.Println(ok, err)
Output: true <nil>
func IsValidEnum ¶ added in v0.1.1
func IsValidEnum(enum string, allowedValues *[]string, emptyValueAllowed bool) (success bool, err error)
IsValidEnum validates an enum given the required parameters and tests if the supplied value is valid from accepted values
Example (Invalid) ¶
ExampleIsValidEnum_invalid example of an invalid enum
testAcceptedValues := []string{"123"} ok, err := IsValidEnum("1", &testAcceptedValues, false) // Invalid fmt.Println(ok, err)
Output: false value 1 is not allowed
Example (Valid) ¶
ExampleIsValidEnum_valid example of an valid enum
testAcceptedValues := []string{"123"} ok, err := IsValidEnum("123", &testAcceptedValues, false) // Valid fmt.Println(ok, err)
Output: true <nil>
func IsValidHost ¶ added in v0.1.7
IsValidHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name
Example (Invalid) ¶
ExampleIsValidHost_invalid example of an invalid host
ok := IsValidHost("-localhost") fmt.Println(ok)
Output: false
Example (Valid) ¶
ExampleIsValidHost_valid example of a valid host
ok := IsValidHost("localhost") fmt.Println(ok)
Output: true
func IsValidIP ¶ added in v0.1.7
IsValidIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP`
Example (Invalid) ¶
ExampleIsValidIP_invalid example of an invalid ip address
ok := IsValidIP("300.0.0.0") fmt.Println(ok)
Output: false
Example (Valid) ¶
ExampleIsValidIP_valid example of a valid ip address
ok := IsValidIP("127.0.0.1") fmt.Println(ok)
Output: true
func IsValidIPv4 ¶ added in v0.1.7
IsValidIPv4 check if the string is IP version 4.
func IsValidIPv6 ¶ added in v0.1.7
IsValidIPv6 check if the string is IP version 6.
func IsValidPhoneNumber ¶ added in v0.1.2
IsValidPhoneNumber validates a given phone number and country code
Example (Invalid) ¶
ExampleIsValidPhoneNumber_invalid example of an invalid phone number
countryCode := "+1" phone := "555-444-44" ok, err := IsValidPhoneNumber(phone, countryCode) fmt.Println(ok, err)
Output: false phone number must be ten digits
Example (Valid) ¶
ExampleIsValidPhoneNumber_valid example of a valid phone number
countryCode := "+1" ok, err := IsValidPhoneNumber(testPhone, countryCode) fmt.Println(ok, err)
Output: true <nil>
func IsValidSocial ¶ added in v0.1.1
IsValidSocial validates the USA social security number using ATS rules
Example (Invalid) ¶
ExampleIsValidSocial_invalid example of an invalid social response
ok, err := IsValidSocial("666-00-0000") // Invalid fmt.Println(ok, err)
Output: false social section was found invalid (cannot be 000 or 666)
Example (Valid) ¶
ExampleIsValidSocial_invalid example of a valid social response
ok, err := IsValidSocial("212126768") // Valid fmt.Println(ok, err)
Output: true <nil>
Types ¶
type Interface ¶
type Interface interface { // SetFieldIndex stores the index of the field SetFieldIndex(index int) // FieldIndex retrieves the index of the field FieldIndex() int // SetFieldName stores the name of the field SetFieldName(name string) // FieldName retrieves the name of the field FieldName() string // Validate determines if the value is valid. The value nil is returned if it is valid Validate(value interface{}, obj reflect.Value) *ValidationError }
Interface specifies the necessary methods a validation must implement to be compatible with this package
type Map ¶
type Map struct {
// contains filtered or unexported fields
}
Map is an atomic validation map, and when two sets happen at the same time, the latest that started wins.
func (*Map) AddValidation ¶
AddValidation registers the validation specified by a key to the known validations. If more than one validation registers with the same key, the last one will become the validation for that key.
func (*Map) IsValid ¶
func (m *Map) IsValid(object interface{}) (bool, []ValidationError)
IsValid will either store the builder interfaces or run the IsValid based on the reflection object type
type Validation ¶
type Validation struct { // Name of the validation Name string // contains filtered or unexported fields }
Validation is an implementation of an Interface and can be used to provide basic functionality to a new validation type through an anonymous field
func (*Validation) FieldIndex ¶
func (v *Validation) FieldIndex() int
FieldIndex retrieves the index of the field the validation was applied to
func (*Validation) FieldName ¶
func (v *Validation) FieldName() string
FieldName retrieves the name of the field the validation was applied to
func (*Validation) SetFieldIndex ¶
func (v *Validation) SetFieldIndex(index int)
SetFieldIndex stores the index of the field the validation was applied to
func (*Validation) SetFieldName ¶
func (v *Validation) SetFieldName(name string)
SetFieldName stores the name of the field the validation was applied to
func (*Validation) Validate ¶
func (v *Validation) Validate(_ interface{}, _ reflect.Value) *ValidationError
Validate determines if the value is valid. The value nil is returned if it is valid
type ValidationError ¶
type ValidationError struct { // Key is the Field name, key name Key string // Message is the error message Message string }
ValidationError is the key and message of the corresponding error
func IsValid ¶
func IsValid(object interface{}) (bool, []ValidationError)
IsValid determines if an object is valid based on its validation tags using DefaultMap.
Example (CompareString) ¶
ExampleIsValid_CompareString is an example for compare string validation
type User struct { // Password should match confirmation on submission Password string `validation:"compare=PasswordConfirmation"` PasswordConfirmation string } var u User // User submits a new password and confirms wrong u.Password = "This" u.PasswordConfirmation = "That" ok, errs := IsValid(u) fmt.Println(ok, errs)
Output: false [{Password is not the same as the compare field PasswordConfirmation}]
Example (FormatEmail) ¶
ExampleIsValid_FormatEmail is an example for format email validation
type Person struct { // Email must be in valid email format Email string `validation:"format=email"` } var p Person // Will fail since the email is not valid ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Email does not match email format}]
Example (FormatRegEx) ¶
ExampleIsValid_FormatRegEx is an example for format regex validation
type Person struct { // Phone must be in valid phone regex format Phone string `validation:"format=regexp:[0-9]+"` } var p Person // Will fail since the email is not valid ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Phone does not match regexp format}]
Example (MaxFloat) ¶
ExampleIsValid_MaxFloat is an example for Float Value validation (max)
type Product struct { // Price must more than 0.01 but less than 999.99 Price float32 `validation:"min=0.01 max=999.99"` } var p Product p.Price = 10000.00 // Will fail since it's greater than 999.99 ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Price must be less than or equal to 9.9999E+02}]
Example (MaxInt) ¶
ExampleIsValid_MaxInt is an example for Int Value validation (max)
type Product struct { // Quantity must more than 1 but less than 99 Quantity int8 `validation:"min=1 max=99"` } var p Product p.Quantity = 101 // Will fail since it's greater than 99 ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Quantity must be less than or equal to 99}]
Example (MaxLength) ¶
ExampleIsValid_MaxLength is an example for max length validation (max)
type Person struct { // Gender must not be longer than 10 characters Gender string `validation:"max_length=10"` } var p Person p.Gender = "This is invalid!" // Will fail since it's > 10 characters ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Gender must be no more than 10 characters}]
Example (MinFloat) ¶
ExampleIsValid_MinFloat is an example for Float Value validation (min)
type Product struct { // Price must more than 0.01 Price float32 `validation:"min=0.01"` } var p Product // Will fail since its Price = 0 ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Price must be greater than or equal to 1E-02}]
Example (MinInt) ¶
ExampleIsValid_MinInt is an example for Int Value validation (min)
type Product struct { // Quantity must more than 1 Quantity int8 `validation:"min=1"` } var p Product // Will fail since its Quantity = 0 ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Quantity must be greater than or equal to 1}]
Example (MinLength) ¶
ExampleIsValid_MinLength is an example for min length validation (min)
type Person struct { // Gender must be > 1 character Gender string `validation:"min_length=1"` } var p Person // Will fail since it's < 1 character ok, errs := IsValid(p) fmt.Println(ok, errs)
Output: false [{Gender must be at least 1 characters}]
func (*ValidationError) Error ¶
func (v *ValidationError) Error() string
ValidationError returns a string of a key + a message
Example ¶
ExampleValidationError_Error is showing how to use the errors
type Person struct { // Gender must not be longer than 10 characters Gender string `validation:"max_length=10"` } var p Person p.Gender = "This is invalid!" // Will fail since it's > 10 characters _, errs := IsValid(p) fmt.Println(errs[0].Error())
Output: Gender must be no more than 10 characters
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors is a slice of validation errors
func (ValidationErrors) Error ¶
func (v ValidationErrors) Error() (errors string)
ValidationError returns the list of errors from the slice of errors
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
model
command
Package main is an example of using the "validate package" in a basic model (validating data before persisting into a database)
|
Package main is an example of using the "validate package" in a basic model (validating data before persisting into a database) |