feat(json-schema-2020-12): add support for string validation keywords (#8625)

Includes following keywords:

- minLength
- maxLength
- pattern


Refs #8513
This commit is contained in:
Vladimír Gorej
2023-05-08 12:37:31 +02:00
committed by GitHub
parent 1a29662977
commit facd5ace25
3 changed files with 52 additions and 5 deletions

View File

@@ -3,14 +3,27 @@
*/
import React from "react"
import PropTypes from "prop-types"
import classNames from "classnames"
/**
* This component represents various constraint keywords
* from JSON Schema 2020-12 validation vocabulary.
*/
const Constraint = ({ constraint }) => (
<span className="json-schema-2020-12__constraint">{constraint}</span>
)
const Constraint = ({ constraint }) => {
const isPattern = /^matches /.test(constraint)
const isStringRange = /characters/.test(constraint)
const isStringRelated = isPattern || isStringRange
return (
<span
className={classNames("json-schema-2020-12__constraint", {
"json-schema-2020-12__constraint--string-related": isStringRelated,
})}
>
{constraint}
</span>
)
}
Constraint.propTypes = {
constraint: PropTypes.string.isRequired,

View File

@@ -6,4 +6,9 @@
color: white;
background-color: #805AD5;
border-radius: 4px;
&--string-related {
color: white;
background-color: #D69E2E;
}
}

View File

@@ -231,15 +231,44 @@ const stringifyConstraintNumberRange = (schema) => {
return null
}
const stringifyConstraintRange = (label, min, max) => {
const hasMin = typeof min === "number"
const hasMax = typeof max === "number"
if (hasMin && hasMax) {
if (min === max) {
return `${min} ${label}`
} else {
return `[${min}, ${max}] ${label}`
}
}
if (hasMin) {
return `>= ${min} ${label}`
}
if (hasMax) {
return `<= ${max} ${label}`
}
return null
}
export const stringifyConstraints = (schema) => {
const constraints = []
// Validation Keywords for Numeric Instances (number and integer)
// validation Keywords for Numeric Instances (number and integer)
const constraintMultipleOf = stringifyConstraintMultipleOf(schema)
if (constraintMultipleOf !== null) constraints.push(constraintMultipleOf)
const constraintNumberRange = stringifyConstraintNumberRange(schema)
if (constraintNumberRange !== null) constraints.push(constraintNumberRange)
// validation Keywords for Strings
const constraintStringRange = stringifyConstraintRange(
"characters",
schema?.minLength,
schema?.maxLength
)
if (constraintStringRange !== null) constraints.push(constraintStringRange)
if (schema?.pattern) constraints.push(`matches ${schema?.pattern}`)
return constraints
}