Skip to content

Repository files navigation

Go Validator Package

Go ReferenceVersion: v1.0.0License
Validator is a ligth package that allows you to validate over Go Structures and Tags. You can start using directly by adding the relevant tags to the structures you have created.

With the Validator package you can:

  • You can perform many validation processes through the structures you have created.
  • In case of validation fail, you can receive error messages in eight languages. [see. supported languages]
  • You can change the validation error messages as you wish.
  • You can implement your own validation functions.

For Whom?
If you want to perform basic validations in a simple way, feel free to use this package.

Installation

Use go get:
go get github.com/sschrs/validator

Then import:
import “github.com/sschrs/validator”

Usage and Documentation

Basic Usage

Declare a struct with validate tags:

typeUserstruct {
Namestring`validate:"notNull,gt=1"`//not null and length must be greater than 1Emailstring`validate:"email"`Phonestring`validate:"eq=11,numeric"`//numeric and length must be equal to 11Ageint`validate:"gte=18"`//age must be greater than or equal to 18Passordstring`validate:"containsString,containsNumber,containsSpecialChars"`
}

Use Validate() function to validate it:

funcmain() {
varuserUseruser.Name="John Doe"user.Email="example"ifisValid, message:=validator.Validate(&user); !isValid {
fmt.Println(message)
}
}

Change Default Language

You can use the validator.ChangeDefaultLanguage() function to change the default language. Available languages: English, German, Turkish, French, Italian, Spanish, Dutch, Portuguese

validator.ChangeDefaultLanguage("tr") //Change language to turkish

Change Default Tag Name

If you want to change the tag name, you can use the validator.ChangeTagName() function. This function returns the current tag name. A string value containing '=' sign is not accepted and the tag name won't change.

newTagName:=validator.ChangeTagName("validator")

Change Default Special Chars

The default characters for containsSpecialChars validation are: [@#$%^&+!?.,;:] If you want to change these characters, you can use the validator.ChangeSpecialChars() function. The "=" sign is not accepted and no change is made if it is sent as a parameter. This function returns new special characters.

newSpecialChars:=validator.ChangeSpecialChars("?=&!")

Change Validation Message

You can use the validator.ChangeMessage() function to change the message body. This function takes two parameters, the first validation name and the second new message body, and returns an error if it cannot find a valid validation.

err:=validator.ChangeMessage("notNull", "new message for notNull validation")

Add Custom Validation Func

The AddCustomValidation() function can be used to add a custom validation function. This function takes two parameters, the first validation name and the second validation function.
First, let's examine the structure of the validation function. This function takes a structure of type validator.Field and a value of type string as a parameter.

funcvalidationFunc(field validator.Field,valuestring) (bool,string){}

The field structure is as follows. The name value is the name of the fields in the structure. Value is the value of this field, and tag is the tag corresponding to this field.

typeFieldstruct {
NamestringValue reflect.ValueTagstring
}

The second parameter of the validation function represents the value of the validation rule separated by '=', if any.

Sample 1

Custom validation function that checks if the value of the structure's field contains an '&' sign.

validator.AddCustomValidation("containsAmp", func(field validator.Field, valuestring) (bool, string) {
if!strings.Contains(field.Value.String(), "&") {
returnfalse, fmt.Sprintf("%s field must containt '&'", field.Name)
}
returntrue, ""
})
typeSstruct {
Textstring`validate:"containsAmp"`// U can use with validation name in the tags
}

Sample 2

The custom validation function, which checks whether the number is divisible by the given value, is as follows.

validator.AddCustomValidation("divisible", func(field validator.Field, _valuestring) (bool, string) {
value, err:=strconv.Atoi(_value)
iferr!=nil {
panic("the value can not convert to int")
}
iffield.Value.Int()%int64(value) !=0 {
returnfalse, fmt.Sprintf("%s field must be divisible by %d", field.Name, value)
}
returntrue, ""
})
typeSstruct {
Numberint`validate:"divisible=3"`
}

Validation Tags

TagValidation
notNullnot null
emailemail
numericnumeric,just numbers
containsStringmust contain at least one character
containsNumbermust contain at least one number
containsSpecialCharsmust contain at least one special character(Default:[@#$%^&+!?.,;:])
eqequal
gtgreater than
ltless than
gtegreater than or equal
lteless than or equal
nenot equal
containsmust contain the given value
notContainsmust not contain the given value
beginmust begin with given value
notBeginmust not begin with given value
endmust end with given value
notEndmust not end with given value

eq,ne,gt,gte,lt,lte -> Length for string expressions and values for numeric expressions are compared.

Supported Languages

LanguageCode
Englishen
Germande
Turkishtr
Frenchfr
Spanishes
Dutchnl
Portuguesepr

About

A light package for validating structures in the go programming language.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages