0

0

Simplifying String Validation in Go: Introducing validatorgo

霞舞

霞舞

发布时间:2024-11-15 10:27:44

|

345人浏览过

|

来源于dev.to

转载

simplifying string validation in go: introducing validatorgo

字符串验证器和清理器的库,基于 js 库 validator.js

为什么选择验证器go?

为什么不使用流行的 go 库,如 package validator 或 govalidator?虽然这两个库都很出名,但 validatorgo 专注于独立字符串验证,并提供了受 validator.js 启发的广泛的可定制验证器集合,而这两个 go 库都没有完全实现。

以下是 validatorgo 与 go-playground/validator 和 govalidator 相比的突出之处:


1. 与 go-playground/validator 相比

  • 直接字符串验证:go-playground/validator 主要用于使用标签验证结构字段,这非常适合处理 json 或基于结构的数据。然而,它并不是为验证单个字符串而设计的,validatorgo 可以无缝地验证单个字符串,而不需要结构标签或额外的设置。

  • 性能:go-playground/validator 依赖反射来动态检查结构标签。反射虽然功能强大,但会带来性能开销,尤其是在验证大型或复杂数据结构时。 validatorgo 避免了反射,从而提高了性能,对于需要单字段验证的场景来说,速度更快、效率更高。


2. 与 asasskevich/govalidator 相比

  • 定制和灵活性:govalidator 为字符串提供了一系列验证器,但是 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 包名称,您可以这样做。

FaceSwapper
FaceSwapper

FaceSwapper是一款AI在线换脸工具,可以让用户在照片和视频中无缝交换面孔。

下载
 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 如果您需要的话,是理想的选择:

  • 针对各个字段进行高效、无反射的验证,而不会产生与基于结构的反射相关的性能成本。
  • 高度可定制与现代数据格式一致的验证选项,提供与 validator.js 相同的稳健性。

使用 validatorgo,您将获得专门为字符串验证而设计的工具,支持 go 中的独立和 web 应用程序要求。

维护者

  • bube054 - attah gbubemi david(作者)

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

420

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

536

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

313

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

77

2025.09.10

string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

503

2023.08.02

java中boolean的用法
java中boolean的用法

在Java中,boolean是一种基本数据类型,它只有两个可能的值:true和false。boolean类型经常用于条件测试,比如进行比较或者检查某个条件是否满足。想了解更多java中boolean的相关内容,可以阅读本专题下面的文章。

351

2023.11.13

java boolean类型
java boolean类型

本专题整合了java中boolean类型相关教程,阅读专题下面的文章了解更多详细内容。

32

2025.11.30

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

783

2023.08.22

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

54

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 3.2万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.5万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号