我的任务是用Skooma库https://github.com/bobfp/skooma#validators实现输入验证器。
一般的概念是非常清楚的,但是对于一些输入,我有一个“合法”的单词列表,我对如何实现这种情况的验证没有任何线索。因此,我来到这里,我想问你是否知道任何使用这个库的例子/项目?我搜索了但什么也没找到。如果你还有其他小费就告诉我!这是一个例子:
我的模式:
schema = %{
:titel => :string,
:category => :string,
:high_level_category => :string,
:description => :string,
:potential_impacts => :string,
:affected_assets => :string,
:rating => :string }对类别的法律投入:
category = %{core: 'Core network threats', access: 'Access network threats', multi: 'Multi edge computing threats',
virtualisation: 'Virtualisation threats', phyiscal: 'Physical infrastructure threats', generic: 'Generic threats'}我也尝试了一个正常的列表,例如
category = ['Core network threats', 'Access network threats', 'Multi edge computing threats' .......]但我只是不知道如何检查:类别是否存在于类别列表中。
发布于 2022-01-31 00:05:07
您需要一个自定义验证器函数,下面是一个示例:
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日)发表。
https://stackoverflow.com/questions/70913797
复制相似问题