1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/gookit-validate

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
Клонировать/Скачать
Внести вклад в разработку кода
Синхронизировать код
Отмена
Подсказка: Поскольку Git не поддерживает пустые директории, создание директории приведёт к созданию пустого файла .keep.
Loading...
README.md

Можно настроить сообщение об ошибке валидатора

Translates() map[string]string можно настроить перевод полей.

package main

import (
    "fmt"
    "time"

    "github.com/gookit/validate"
)

// UserForm struct
type UserForm struct {
    Name     string    `validate:"required|min_len:7"`
    Email    string    `validate:"email"`
    Age      int       `validate:"required|int|min:1|max:99"`
    CreateAt int       `validate:"min:1"`
    Safe     int       `validate:"-"`
    UpdateAt time.Time `validate:"required"`
    Code     string    `validate:"customValidator"`
    // ExtInfo nested struct
    ExtInfo struct{
        Homepage string `validate:"required"`
        CityName string
    } `validate:"required"`
}

// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
    return len(val) == 4
}

// ConfigValidation config the Validation
// eg:
// - define validate scenes
func (f UserForm) ConfigValidation(v *validate.Validation) {
    v.WithScenes(validate.SValues{
        "add":    []string{"ExtInfo.Homepage", "Name", "Code"},
        "update": []string{"ExtInfo.CityName", "Name"},
    })
}

// Messages you can custom validator error messages. 
func (f UserForm) Messages() map[string]string {
    return validate.MS{
        "required": "о! поле {field} обязательно для заполнения",
        "email": "некорректный адрес электронной почты",
        "Name.required": "сообщение для специального поля",
        "Age.int": "возраст должен быть целым числом",
        "Age.min": "минимальное значение возраста — 1",
    }
}

// Translates you can custom field translates. 
func (f UserForm) Translates() map[string]string {
    return validate.MS{
        "Имя": "Имя пользователя",
        "Email": "Электронная почта пользователя",
        "ExtInfo.Домашняя страница": "Домашняя страница",
    }
}

Создание и проверка

Можно использовать validate.Struct(ptr) для быстрого создания экземпляра проверки. Затем вызвать v.Validate() для проверки.

package main

import (
  "fmt"

  "github.com/gookit/validate"
)

func main() {
    u := &UserForm{
        Name: "inhere",
    }
    
    v := validate.Struct(u)
    // v := validate.New(u)

    if v.Validate() { // проверка прошла успешно
        // сделать что-то ...
    } else {
        fmt.Println(v.Errors) // все сообщения об ошибках
        fmt.Println(v.Errors.One()) // возвращает случайное текстовое сообщение об ошибке
        fmt.Println(v.Errors.OneError()) // возвращает одну ошибку
        fmt.Println(v.Errors.Field("Name")) // возвращает сообщения об ошибках поля 
    }
}

Проверка карты

Также можно проверить данные карты напрямую.

package main

import (
"fmt"

"github.com/gookit/validate"
)

func main()  {
    m := map[string]interface{}{
        "name":  "inhere",
        "age":   100,
        "oldSt": 1,
        "newSt": 2,
        "email": "some@email.com",
        "tags": []string{"go", "php", "java"},
    }

    v := validate.Map(m)
    // v := validate.New(m)
    v.AddRule("name", "required")
    v.AddRule("name", "minLen", 7)
    v.AddRule("age", "max", 99)
    v.AddRule("age", "min", 1)
    v.AddRule("email", "email")
    
    // также можно
    v.StringRule("age", "required|int|min:1|max:99")
    v.StringRule("name", "required|minLen:7")
    v.StringRule("tags", "required|slice|minlen:1")
    // особенность: поддержка проверки подэлемента в срезе
    v.StringRule("tags.*", "required|string|min_len:7")

    // v.WithScenes(map[string]string{
    //   "create": []string{"name", "email"},
    //   "update": []string{"name"},
    // })
    
    if v.Validate() { // проверка пройдена
        безопасные данные := v.SafeData()
        // сделать что-то...
    } иначе {
        fmt.Println(v.Errors) // все сообщения об ошибках
        fmt.Println(v.Errors.One()) // возвращает случайное текстовое сообщение об ошибке
    }
}

Проверить запрос

Если это HTTP-запрос, вы можете быстро проверить данные и передать проверку. Затем привяжите защищённые данные к структуре. ``` time.Time Code string }

func main() { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { data, err := validate.FromRequest(r) if err != nil { panic(err) }

    v := data.Create()
    // setting rules
    v.FilterRule("age", "int") // convert value to int

    v.AddRule("name", "required")
    v.AddRule("name", "minLen", 7)
    v.AddRule("age", "max", 99)
    v.StringRule("code", `required|regex:\d{4,6}`)

    if v.Validate() { // validate ok
        // safeData := v.SafeData()
        userForm := &UserForm{}
        v.BindSafeData(userForm)

        // do something ...
        fmt.Println(userForm.Name)
    } else {
        fmt.Println(v.Errors) // all error messages
        fmt.Println(v.Errors.One()) // returns a random error message text
    }
})

http.ListenAndServe(":8090", handler)

}


## Quick Method

Quick create Validation instance.

- New(data interface{}, scene ...string) *Validation
- Request(r *http.Request) *Validation
- JSON(s string, scene ...string) *Validation
- Struct(s interface{}, scene ...string) *Validation
- Map(m map[string]interface{}, scene ...string) *Validation

Quick create DataFace instance.

- FromMap(m map[string]interface{}) *MapData
- FromStruct(s interface{}) (*StructData, error)
- FromJSON(s string) (*MapData, error)
- FromJSONBytes(bs []byte) (*MapData, error)
- FromURLValues(values url.Values) *FormData
- FromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error)

> Create Validation from DataFace

```go
d := FromMap(map[string]interface{}{"key": "val"})
v := d.Validation()

Methods In Validation

  • func (v *Validation) Validate(scene ...string) bool Do validating and return is success.
  • func (v *Validation) ValidateE(scene ...string) Errors Do validating and return error.

More Usage

Validate Error

v.Errors is map data, top key is field name, value is map[string]string.

// do validating
if v.Validate() {
    return nil
}

// get errors
es := v.Errors

// check
es.Empty() // bool

// returns an random error, if no error returns nil
fmt.Println(v.Errors.OneError())
fmt.Println(v.Errors.ErrOrNil())

fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.Field("Name")) // returns error messages of the field 

Encode to JSON:

  • StopOnError=true(default), will only one error
{
    "field1": {
        "required": "error msg0"
    }
}
  • if StopOnError=false, will get multi error
{
    "field1": {
        "minLen": "error msg1",
        "required": "error msg0"
    },
    "field2": {
        "min": "error msg2"
    }
}

Global Option

You can adjust some processing logic of the validator by changing the global option settings.

// GlobalOption settings for validate
type GlobalOption struct {
    // FilterTag name in the struct tags.
    //
    // default: filter
    FilterTag string
    // ValidateTag in the struct tags.
    //
    // default: validate
    ValidateTag string
    // FieldTag the output field name in the struct tags.
    // it as placeholder on error message.
    //
    // default: json
    FieldTag string
    // LabelTag the display name in the struct tags.
    // use for define field translate name on error.
    //
    // default: label
    LabelTag string
    // MessageTag define error message for the field.
    //
    // default: message
    MessageTag string
    // StopOnError If true: An error occurs, it will cease to continue to verify
    StopOnError bool
    // SkipOnEmpty Skip check on field not exist or value is empty
    SkipOnEmpty bool
    // UpdateSource Whether to update source field value, useful for struct validate
    UpdateSource bool
    // CheckDefault Whether to validate the default value set by the user
    CheckDefault bool
    // CheckZero Whether validate the default zero value. (intX,uintX:
``` **Текст запроса:**

value is IPv6 string.
`CIDR/isCIDR` | Check value is CIDR string.
`CIDRv4/isCIDRv4` | Check value is CIDRv4 string.
`CIDRv6/isCIDRv6` | Check value is CIDRv6 string.
`uuid/isUUID` | Check value is UUID string.
`uuid3/isUUID3` | Check value is UUID3 string.
`uuid4/isUUID4` | Check value is UUID4 string.
`uuid5/isUUID5` | Check value is UUID5 string.
`filePath/isFilePath` | Check value is an existing file path
`unixPath/isUnixPath` | Check value is Unix Path string.
`winPath/isWinPath` | Check value is Windows Path string.
`isbn10/ISBN10/isISBN10` | Check value is ISBN10 string.
`isbn13/ISBN13/isISBN13` | Check value is ISBN13 string.  

**Notice:**
- `intX` is contains: int, int8, int16, int32, int64
- `uintX` is contains: uint, uint8, uint16, uint32, uint64
- `floatX` is contains: float32, float64  

<a id="built-in-filters"></a>
## Built In Filters

> Filters powered by: [gookit/filter](https://github.com/gookit/filter)

filter/aliases | description 
-------------------|-------------------------------------------
`int/toInt`  | Convert value(string/intX/floatX) to `int` type `v.FilterRule("id", "int")`
`uint/toUint`  | Convert value(string/intX/floatX) to `uint` type `v.FilterRule("id", "uint")`
`int64/toInt64`  | Convert value(string/intX/floatX) to `int64` type `v.FilterRule("id", "int64")`
`float/toFloat`  | Convert value(string/intX/floatX) to `float` type
`bool/toBool`   | Convert string value to bool. (`true`: "1", "on", "yes", "true", `false`: "0", "off", "no", "false")
`trim/trimSpace`  | Clean up whitespace characters on both sides of the string
`ltrim/trimLeft`  | Clean up whitespace characters on left sides of the string
`rtrim/trimRight`  | Clean up whitespace characters on right sides of the string
`int/integer`  | Convert value(string/intX/floatX) to int type `v.FilterRule("id", "int")`
`lower/lowercase` | Convert string to lowercase
`upper/uppercase` | Convert string to uppercase
`lcFirst/lowerFirst` | Convert the first character of a string to lowercase
`ucFirst/upperFirst` | Convert the first character of a string to uppercase
`ucWord/upperWord` | Convert the first character of each word to uppercase
`camel/camelCase` | Convert string to camel naming style
`snake/snakeCase` | Convert string to snake naming style
`escapeJs/escapeJS` | Escape JS string.
`escapeHtml/escapeHTML` | Escape HTML string.
`str2ints/strToInts` | Convert string to int slice `[]int` 
`str2time/strToTime` | Convert date string to `time.Time`.
`str2arr/str2array/strToArray` | Convert string to string slice `[]string`

## Gookit packages

- [gookit/ini](https://github.com/gookit/ini) Go config management, use INI files
- [gookit/rux](https://https://github.com/gookit/rux) Simple and fast request router for golang HTTP 
- [gookit/gcli](https://github.com/gookit/gcli) build CLI application, tool library, running CLI commands
- [gookit/event](https://github.com/gookit/event) Lightweight event manager and dispatcher implements by Go
- [gookit/cache](https://github.com/gookit/cache) Generic cache use and cache manager for golang. support File, Memory, Redis, Memcached.
- [gookit/config](https://github.com/gookit/config) Go config management. support JSON, YAML, TOML, INI, HCL, ENV and Flags
- [gookit/color](https://github.com/gookit/color) A command-line color library with true color support, universal API methods and Windows support
- [gookit/filter](https://github.com/gookit/filter) Provide filtering, sanitizing, and conversion of golang data
- [gookit/validate](https://github.com/gookit/validate) Use for data validation and filtering. support Map, Struct, Form data
- [gookit/goutil](https://github.com/gookit/goutil) Some utils for the Go: string, array/slice, map, format, cli, env, filesystem, test and more
- More please see https://github.com/gookit

## See also

- https://github.com/albrow/forms
- https://github.com/asaskevich/govalidator
- https://github.com/go-playground/validator
- https://github.com/inhere/php-validate

## License

**[MIT](LICENSE)**

В запросе идёт речь о фильтрах и пакетах для разработки на языке Go. В тексте описаны фильтры, которые используются для преобразования данных в различные типы, а также пакеты, предоставляющие различные утилиты для работы с данными.

Комментарии ( 0 )

Вы можете оставить комментарий после Вход в систему

Введение

Go — универсальная библиотека для проверки и фильтрации данных. Простая в использовании, содержит большинство часто используемых валидаторов и фильтров, поддерживает пользовательские валидаторы, настраиваемые сообщения об ошибках и перевод полей. Развернуть Свернуть
MIT
Отмена

Обновления

Пока нет обновлений

Участники

все

Недавние действия

Загрузить больше
Больше нет результатов для загрузки
1
https://api.gitlife.ru/oschina-mirror/gookit-validate.git
git@api.gitlife.ru:oschina-mirror/gookit-validate.git
oschina-mirror
gookit-validate
gookit-validate
master