当前位置:首页 > 文章列表 > Golang > Go教程 > Simplifying String Validation in Go: Introducing validatorgo

Simplifying String Validation in Go: Introducing validatorgo

来源:dev.to 2024-11-17 14:58:06 0浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《Simplifying String Validation in Go: Introducing validatorgo》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

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 包名称,您可以这样做。

 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(作者)

今天关于《Simplifying String Validation in Go: Introducing validatorgo》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
Win7如何修改切换窗口数量? win7修改切换窗口数量的方法Win7如何修改切换窗口数量? win7修改切换窗口数量的方法
上一篇
Win7如何修改切换窗口数量? win7修改切换窗口数量的方法
UC浏览器电脑版怎么样?
下一篇
UC浏览器电脑版怎么样?
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • PubMedQA数据集详解:生物医学问答基准、功能与应用指南
    PubMedQA
    深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
    804次使用
  • H2O EvalGPT:开源LLM大模型评估与排行榜工具
    H2O EvalGPT
    H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
    795次使用
  • LMArena是什么?伯克利AI模型评估平台使用指南与功能解析
    LMArena
    LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
    883次使用
  • 斯坦福HELM:大语言模型Holistic Evaluation整体评估框架详解
    HELM
    深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
    852次使用
  • MMBench详解:多模态大模型基准测试、功能特点与使用指南
    MMBench
    MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
    683次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议 和 隐私政策
返回登录
  • 重置密码