为组合字段值添加最小长度条件
Add a minlength condition for combined field values
我的表单中有名字和姓氏字段,我需要强制执行一个规则,即名字和姓氏的总长度应至少为 4 个字符。这在 JSON 模式 v4 验证器中可能吗?我的 JSON 看起来像这样:
{
"first_name" : "Fo",
"last_name" : "L",
.....
}
我无法在表单中保留 full_name 字段 - 它需要是两个单独的字段 first_name 和 last_name。我知道一种方法是在后端连接名字和姓氏,然后有一个像这样的验证器:
$full_name = $first_name + $last_name;
--------------------------------------
"full_name": {
"type": "string",
"error_code": "incorrect_length",
"anyOf": [
{ "minLength": 4 },
{ "maxLength": 0 }
]
},
但是,我正在研究一种不必创建虚拟 full_name 字段的方法。是否可以仅使用 first_name 和 last_name 字段进行验证?
这可以通过 JSON Schema 实现,尽管不是很好的方式,最好在后端进行。没有关键字来实现这一目标,因此您必须使用 oneOf
并覆盖有效案例,如下所示:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"oneOf": [
{
"properties": {
"first_name": {
"minLength": 1
},
"last_name": {
"minLength": 3
}
}
},
{
"properties": {
"first_name": {
"minLength": 2
},
"last_name": {
"minLength": 2
}
}
},
{
"properties": {
"first_name": {
"minLength": 3
},
"last_name": {
"minLength": 1
}
}
}
]
}
我的表单中有名字和姓氏字段,我需要强制执行一个规则,即名字和姓氏的总长度应至少为 4 个字符。这在 JSON 模式 v4 验证器中可能吗?我的 JSON 看起来像这样:
{
"first_name" : "Fo",
"last_name" : "L",
.....
}
我无法在表单中保留 full_name 字段 - 它需要是两个单独的字段 first_name 和 last_name。我知道一种方法是在后端连接名字和姓氏,然后有一个像这样的验证器:
$full_name = $first_name + $last_name;
--------------------------------------
"full_name": {
"type": "string",
"error_code": "incorrect_length",
"anyOf": [
{ "minLength": 4 },
{ "maxLength": 0 }
]
},
但是,我正在研究一种不必创建虚拟 full_name 字段的方法。是否可以仅使用 first_name 和 last_name 字段进行验证?
这可以通过 JSON Schema 实现,尽管不是很好的方式,最好在后端进行。没有关键字来实现这一目标,因此您必须使用 oneOf
并覆盖有效案例,如下所示:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"oneOf": [
{
"properties": {
"first_name": {
"minLength": 1
},
"last_name": {
"minLength": 3
}
}
},
{
"properties": {
"first_name": {
"minLength": 2
},
"last_name": {
"minLength": 2
}
}
},
{
"properties": {
"first_name": {
"minLength": 3
},
"last_name": {
"minLength": 1
}
}
}
]
}