首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Skooma输入验证器

Skooma输入验证器
EN

Stack Overflow用户
提问于 2022-01-30 10:31:08
回答 1查看 41关注 0票数 0

我的任务是用Skooma库https://github.com/bobfp/skooma#validators实现输入验证器。

一般的概念是非常清楚的,但是对于一些输入,我有一个“合法”的单词列表,我对如何实现这种情况的验证没有任何线索。因此,我来到这里,我想问你是否知道任何使用这个库的例子/项目?我搜索了但什么也没找到。如果你还有其他小费就告诉我!这是一个例子:

我的模式:

代码语言:javascript
复制
schema = %{
:titel => :string, 
:category => :string, 
:high_level_category => :string, 
:description => :string, 
:potential_impacts => :string, 
:affected_assets => :string, 
:rating => :string }

对类别的法律投入:

代码语言:javascript
复制
category = %{core: 'Core network threats', access: 'Access network threats', multi: 'Multi edge computing threats',
virtualisation: 'Virtualisation threats', phyiscal: 'Physical infrastructure threats', generic: 'Generic threats'}

我也尝试了一个正常的列表,例如

代码语言:javascript
复制
category = ['Core network threats', 'Access network threats', 'Multi edge computing threats' .......]

但我只是不知道如何检查:类别是否存在于类别列表中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-31 00:05:07

您需要一个自定义验证器函数,下面是一个示例:

代码语言:javascript
复制
alias Skooma.Validators

@valid_categories [
  "Access network threats",
  "Core network threats",
  "Generic threats",
  "Multi edge computing threats",
  "Physical infrastructure threats",
  "Virtualisation threats"
]

def valid?(data), do: Skooma.valid?(data, schema())

defp schema,
  do: %{
    :category => [:string, inclusion(@valid_categories)],
    ... # rest of the schema
  }

# copied from:
# https://github.com/bobfp/skooma/blob/master/lib/validators.ex#L38-L48
defp inclusion(values_list) when is_list(values_list) do
  fn data ->
    bool = data in values_list

    if bool do
      :ok
    else
      {:error, "Value is not included in the options: #{inspect(values_list)}"}
    end
  end
end

您可以将inclusion函数替换为Validators.inclusion/1。在这种情况下,您将需要从Github安装Skooma,因为它还没有在今天(2022年1月31日)发表。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70913797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档