
字符串验证器和清理器的库,基于 js 库 validator.js
为什么不使用流行的 go 库,如 package validator 或 govalidator?虽然这两个库都很出名,但 validatorgo 专注于独立字符串验证,并提供了受 validator.js 启发的广泛的可定制验证器集合,而这两个 go 库都没有完全实现。
以下是 validatorgo 与 go-playground/validator 和 govalidator 相比的突出之处:
直接字符串验证:go-playground/validator 主要用于使用标签验证结构字段,这非常适合处理 json 或基于结构的数据。然而,它并不是为验证单个字符串而设计的,validatorgo 可以无缝地验证单个字符串,而不需要结构标签或额外的设置。
性能:go-playground/validator 依赖反射来动态检查结构标签。反射虽然功能强大,但会带来性能开销,尤其是在验证大型或复杂数据结构时。 validatorgo 避免了反射,从而提高了性能,对于需要单字段验证的场景来说,速度更快、效率更高。
我创建了 validatorgo 作为另一个名为 ginvalidator 的 go 库的依赖项,该库验证 go web 应用程序中的 http 请求。受 express-validator(node.js 和 express 的流行验证库)的启发,validatorgo 填补了 go 生态系统中的空白,实现高效、可定制且简单的字符串验证。由于其他库要么矫枉过正,缺乏功能,要么不满足我的用例,我构建了 validatorgo 来提供实用的解决方案。
使用 go get。
go get github.com/bube054/validatorgo
然后将包导入到您自己的代码中。
import ( "fmt" "github.com/bube054/validatorgo" )
如果您不满意使用长 validatorgo 包名称,您可以这样做。
import ( "fmt" vgo "github.com/bube054/validatorgo" )
func main(){
id := "5f2a6c69e1d7a4e0077b4e6b"
validid := vgo.ismongoid(id)
fmt.println(validid) // true
}
下面是 validatorgo 包提供的验证器列表,涵盖了各种字符串格式和类型,使其能够满足多种验证需求。
| validator | description |
|---|---|
| contains | checks if a string contains a specified substring. |
| equals | validates if a string is exactly equal to a comparison string. |
| isabarouting | checks if the string is a valid aba routing number (us bank accounts). |
| isafter | validates if a date string is after a specified date. |
| isalpha | ensures the string contains only letters (a-za-z). |
| isalphanumeric | validates if a string contains only letters and numbers. |
| isascii | checks if the string contains only ascii characters. |
| isbase32 | checks if the string is a valid base32 encoded value. |
| isbase64 | validates if a string is in base64 encoding. |
| isbefore | ensures the date is before a specified date. |
| isboolean | checks if the string is either "true" or "false". |
| iscreditcard | validates if the string is a valid credit card number. |
| iscurrency | checks if the string is a valid currency format. |
| isdate | validates if a string is a valid date. |
| isdecimal | ensures the string represents a valid decimal number. |
| isemail | checks if the string is a valid email address format. |
| isempty | validates if a string is empty. |
| isfqdn | checks if the string is a fully qualified domain name. |
| isfloat | ensures the string represents a floating-point number. |
| ishexcolor | validates if a string is a valid hex color (e.g., #ffffff). |
| isip | checks if the string is a valid ip address (ipv4 or ipv6). |
| isiso8601 | validates if the string is in iso8601 date format. |
| islength | checks if the string’s length is within a specified range. |
| ismimetype | validates if the string is a valid mime type. |
| ismobilephone | checks if the string is a valid mobile phone number for specified locales. |
| ismongoid | validates if the string is a valid mongodb objectid. |
| isnumeric | ensures the string contains only numeric characters. |
| ispostalcode | checks if the string is a valid postal code for specified locale. |
| isrfc3339 | validates if the string is in rfc3339 date format. |
| isslug | checks if the string is url-friendly (only letters, numbers, and dashes). |
| isstrongpassword | ensures the string meets common password strength requirements. |
| isurl | validates if the string is a url. |
| isuuid | checks if the string is a valid uuid (versions 1-5). |
| isuppercase | ensures the string is all uppercase. |
| isvat | checks if the string is a valid vat number for specified countries. |
| matches | validates if the string matches a specified regular expression. |
该表应该涵盖 validatorgo 中当前可用的大多数验证器。请务必参阅包的文档以了解每个验证器的更详细用法。
⚠ 注意 当使用需要选项结构(指针或非指针)的验证器时,请始终显式地为所有结构字段提供值。 与 validator.js 中缺少的字段会自动设置为默认值不同,go 使用严格类型。 这意味着布尔值的缺失值默认为 false,数字类型的缺失值默认为 0,等等。 如果您习惯了 javascript 版本,不指定所有字段可能会导致意外行为。
示例
// do this (using the default options specified in the docs)
ok := validatorgo.isfqdn("example", nil)
// or this (explicitly setting all possible fields for the structs)
ok := validatorgo.isfqdn("example", &validatorgo.isfqdnopts{
requiretld: false,
allowunderscores: false,
allowtrailingdot: true,
allownumerictld: false,
ignoremaxlength: true
})
// but rarely this(not explicitly setting all possible fields)
ok := validatorgo.isfqdn("example", &validatorgo.isfqdnopts{ requiretld: false, })
import (
"fmt"
"github.com/bube054/validatorgo/sanitizer"
)
func main(){
str := sanitizer.Whitelist("Hello123 World!", "a-zA-Z")
fmt.Println(str) // "HelloWorld"
}
| sanitizer | description |
|---|---|
| trim | removes whitespace from both ends of the string. |
| ltrim | removes whitespace from the left side of the string. |
| rtrim | removes whitespace from the right side of the string. |
| tolower | converts the entire string to lowercase. |
| toupper | converts the entire string to uppercase. |
| escape | escapes html characters in the string to prevent injection attacks. |
| unescape | reverts escaped html characters back to normal characters. |
| normalizeemail | standardizes an email address, e.g., removing dots in gmail addresses. |
| blacklist | removes characters from the string that match specified characters or patterns. |
| whitelist | retains only characters in the string that match specified characters or patterns. |
| replace | replaces occurrences of a substring with a specified replacement. |
| striplow | removes control characters, optionally allowing some specified ones. |
| trimspace | trims all types of whitespace from both ends of the string. |
| toboolean | converts common truthy and falsy values in strings into boolean true or false. |
| toint | converts a numeric string into an integer, if possible. |
| tofloat | converts a numeric string into a floating-point number, if possible. |
这些清理程序通常用于通过删除或修改潜在不需要或危险的字符来确保数据一致性和安全性。
请务必参考 validatorgo 官方文档,了解每种消毒剂的具体实现和示例。
validatorgo 如果您需要的话,是理想的选择:
使用 validatorgo,您将获得专门为字符串验证而设计的工具,支持 go 中的独立和 web 应用程序要求。
以上就是Simplifying String Validation in Go: Introducing validatorgo的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号