Reputation: 5152
I have a first name and last name field in my form, and I need to enforce a rule that the combined length of the first and last names should be at least 4 characters. Is this possible in JSON schema v4 validator? My JSON looks like this:
{
"first_name" : "Fo",
"last_name" : "L",
.....
}
I cannot keep a full_name field in my form - it needs to be two separate fields first_name and last_name. I know that one way is to concatenate the first and last names in the backend and then have a validator like so:
$full_name = $first_name + $last_name;
--------------------------------------
"full_name": {
"type": "string",
"error_code": "incorrect_length",
"anyOf": [
{ "minLength": 4 },
{ "maxLength": 0 }
]
},
However, I am looking at a method in which I don't have to create a dummy full_name field. Is it possible to validate with the first_name and last_name fields only?
Upvotes: 1
Views: 721
Reputation: 12335
This is possible with JSON Schema, although not in a very nice way, and doing it on the back end is preferable. There's no key word to achive this, so you would have to use oneOf
and cover the valid cases like so:
{
"$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
}
}
}
]
}
Upvotes: 1