RJSF utility functions, constants and types
In version 5, the utility functions from @rjsf/core/utils were refactored into their own library called @rjsf/utils.
These utility functions are separated into two distinct groups.
The first, larger, group are the functions that do NOT require a ValidatorType interface be provided as one of their parameters.
The second, smaller, group are the functions that DO require a ValidatorType interface be provided as a parameter.
There is also a helper function used to create a SchemaUtilsType implementation from a ValidatorType implementation and rootSchema object.
Constants
The @rjsf/utils package exports a set of constants that represent all the keys into various elements of a RJSFSchema or UiSchema that are used by the various utility functions.
In addition to those keys, there is the special ADDITIONAL_PROPERTY_FLAG flag that is added to a schema under certain conditions by the retrieveSchema() utility.
These constants can be found on GitHub here.
Types
Additionally, the Typescript types used by the utility functions represent nearly all the types used by RJSF.
Those types are exported for use by @rjsf/core and all the themes, as well as any customizations you may build.
These types can be found on GitHub here.
ObjectPath — Used by the path utilities (getByPath, setByPath, hasByPath, unsetByPath) to address a value inside a plain object. It is string | number | FieldPathList. A bare string is always a single literal key: 'a.b' means the key 'a.b', never the nested path a → b. To walk a dotted path string, split it explicitly with toPath() first, or pass a FieldPathList ((string | number)[]) of segments. Reads and existence checks resolve own properties only, so inherited members never appear as form data.
SchemaFieldPath — Used when navigating a JSON Schema subtree (for example with getFromSchema and findFieldInSchema on SchemaUtilsType, documented under Validator-based utility functions). It is string | FieldPathList: either a dotted path or an array of segments with the same rules as FieldPathList ((string | number)[]). A numeric segment denotes an array index or an object key that is numeric. Navigation skips only undefined or empty-string segments, so segment 0 is always honored (this avoids the bug from treating 0 as a falsy path unit).
Enums
There are enumerations in @rjsf/utils that are exported for use by @rjsf/core and all the themes, as well as any customizations you may build.
These enums can be found on GitHub here.
Non-Validator utility functions
allowAdditionalItems()
Checks the schema to see if it is allowing additional items, by verifying that schema.additionalItems is an object.
The user is warned in the console if schema.additionalItems has the value true.
Parameters
- schema: S - The schema object to check
Returns
- boolean: True if additional items is allowed, otherwise false
ariaDescribedByIds()
Return a list of element ids that contain additional information about the field that can be used to as the aria description of the field.
Parameters
- id: FieldPathId | string - Either simple string id or an FieldPathId from which to extract it
- [includeExamples=false]: boolean - Optional flag, if true, will add the
examplesIdinto the list
Returns
- string: The string containing the list of ids for use in an
aria-describedByattribute
asNumber()
Attempts to convert the string into a number. If an empty string is provided, then undefined is returned.
If a null is provided, it is returned.
If the string ends in a . then the string is returned because the user may be in the middle of typing a float number.
If a number ends in a pattern like .0, .20, .030, string is returned because the user may be typing number that will end in a non-zero digit.
Otherwise, the string is wrapped by Number() and if that result is not NaN, that number will be returned, otherwise the string value will be.
Parameters
- value: string | null - The string or null value to convert to a number
Returns
- undefined | null | string | number: The
valueconverted to a number when appropriate, otherwise thevalue
bracketNameGenerator()
Generates bracketed names for form fields.
Parameters
- path: FieldPathList - The path of field path units to use when generating the name
- idPrefix: string - The prefix to use at the start of the generated name
- [isMultiValue]: boolean | undefined - Optional flag, if true, will append
[]to the end of the name for multi-value fields (e.g., checkboxes, multi-select)
Returns
- string: The generated bracketed name (e.g.,
root[tasks][0][title], orroot[hobbies][]for multi-value fields)
buttonId()
Return a consistent id for the btn button element
Parameters
- id: FieldPathId | string - The id of the parent component for the option
- btn: 'add' | 'copy' | 'moveDown' | 'moveUp' | 'remove' - The button type for which to generate the id
Returns
- string: The consistent id for the button from the given
idandbtntype
canExpand<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>()
Checks whether the field described by schema, having the uiSchema and formData supports expanding.
The UI for the field can expand if it has additional properties, is not forced as non-expandable by the uiSchema and the formData object doesn't already have schema.maxProperties elements.
Parameters
- schema: S - The schema for the field that is being checked
- [uiSchema={}]: UiSchema<T, S, F> - The uiSchema for the field
- [formData]: T | undefined - The formData for the field
Returns
- boolean: True if the schema element has additionalProperties or patternProperties keywords, is expandable, and not at the maxProperties limit
createErrorHandler<T = any>()
Given a formData object, recursively creates a FormValidation error handling structure around it
Parameters
- formData: T - The form data around which the error handler is created
Returns
- FormValidation<T>: A
FormValidationobject based on theformDatastructure
dataURItoBlob()
Given the FileReader.readAsDataURL() based dataURI extracts that data into an actual Blob along with the name
of that Blob if provided in the URL. If no name is provided, then the name falls back to unknown.
Parameters
- dataURI: string - The
DataUrlpotentially containing name and raw data to be converted to a Blob
Returns
- { blob: Blob, name: string }: An object containing a Blob and its name, extracted from the URI
dateRangeOptions<S extends StrictRJSFSchema = RJSFSchema>()
Returns a list of options for a date range between start and stop.
If the start date is greater than the end date, then the date range is reversed.
If start and stop are negative numbers (or zero), then they will be treated as relative to the current year.
Parameters
- start: number - The starting point of the date range
- stop: number - The ending point of the date range
Returns
- EnumOptionsType<S>[]: The list of EnumOptionsType for the date range between
startandstop
Throws
- Error when
startandstoparen't both %lt;= 0 or > 0
deepEquals()
Implements a deep equals that treats all functions as equivalent and tracks circular references, so self-referential inputs do not recurse infinitely.
Parameters
- a: any - The first element to compare
- b: any - The second element to compare
Returns
- boolean: True if the
aandbare deeply equal, false otherwise
descriptionId()
Return a consistent id for the field description element.
Parameters
- id: FieldPathId | string - Either simple string id or an FieldPathId from which to extract it
Returns
- string: The consistent id for the field description element from the given
id
dotNotationNameGenerator()
Generates dot-notation names for form fields. Multi-value fields are handled the same as single-value fields in dot notation.
Parameters
- path: FieldPathList - The path of field path units to use when generating the name
- idPrefix: string - The prefix to use at the start of the generated name
- [_isMultiValue]: boolean | undefined - Optional flag (unused in dot notation)
Returns
- string: The generated dot-notation name (e.g.,
root.tasks.0.title)
englishStringTranslator()
Translates a TranslatableString value stringToTranslate into english.
When a params array is provided, each value in the array is used to replace any of the replaceable parameters in the stringToTranslate using the %1, %2, etc. replacement specifiers.
Parameters
stringToTranslate: TranslatableString - The TranslatableString value to convert to english
[params]: string[] - The optional list of replaceable parameter values to substitute to the english string
Returns
- string: The
stringToTranslateitself with any replaceable parameter values substituted
enumOptionsDeselectValue<S extends StrictRJSFSchema = RJSFSchema>()
Removes the enum option value at the valueIndex from the currently selected (list of) value(s).
If selected is a list, then that list is updated to remove the enum option value with the valueIndex in allEnumOptions.
If it is a single value, then if the enum option value with the valueIndex in allEnumOptions matches selected, undefined is returned, otherwise the selected value is returned.
Parameters
- valueIndex: string | number - The index of the value to be removed from the selected list or single value
- [selected]: EnumOptionsType<S>["value"] | EnumOptionsType<S>["value"][] | undefined - The current (list of) selected value(s)
- [allEnumOptions=[]]: EnumOptionsType<S>[] - The list of all the known enumOptions
Returns
- EnumOptionsType<S>["value"][]: The updated
selectedlist with thevalueremoved from it
enumOptionSelectedValue<S extends StrictRJSFSchema = RJSFSchema>()
Computes the value to pass to a select element's value attribute.
When format is 'realValue', converts form data values to strings.
When format is 'indexed' (the default), resolves to index-based values via enumOptionsIndexForValue.
Returns emptyValue when the current value is empty.
Parameters
- value: any - The current form data value
- enumOptions: EnumOptionsType<S>[] | undefined - The available enum options
- multiple: boolean - Whether the select allows multiple selections
- [format='indexed']: OptionValueFormat - How option values are encoded on the DOM
- emptyValue: any - The value to return when the selection is empty
Returns
- any: The value to use for the select element's
valueattribute
enumOptionsIndexForValue<S extends StrictRJSFSchema = RJSFSchema>()
Returns the index(es) of the options in allEnumOptions whose value(s) match the ones in value.
All the enumOptions are filtered based on whether they are a "selected" value and the index of each selected one is then stored in an array.
If multiple is true, that array is returned, otherwise the first element in the array is returned.
Parameters
- value: EnumOptionsType<S>["value"] | EnumOptionsType<S>["value"][] - The single value or list of values for which indexes are desired
- [allEnumOptions=[]]: EnumOptionsType<S>[] - The list of all the known enumOptions
- [multiple=false]: boolean - Optional flag, if true will return a list of index, otherwise a single one
Returns
- string | string[] | undefined: A single string index for the first
valueinallEnumOptions, if notmultiple. Otherwise, the list of indexes for (each of) the value(s) invalue.
enumOptionsIsSelected<S extends StrictRJSFSchema = RJSFSchema>()
Determines whether the given value is (one of) the selected value(s).
Parameters
- value: EnumOptionsType<S>["value"] - The value being checked to see if it is selected
- selected: EnumOptionsType<S>["value"] | EnumOptionsType<S>["value"][] - The current selected value or list of values
- [allEnumOptions=[]]: EnumOptionsType<S>[] - The list of all the known enumOptions
Returns
- boolean: true if the
valueis one of theselectedones, false otherwise
enumOptionsSelectValue<S extends StrictRJSFSchema = RJSFSchema>()
Add the value to the list of selected values in the proper order as defined by allEnumOptions.
Parameters
- valueIndex: string | number - The index of the value that should be selected
- selected: EnumOptionsType<S>["value"][] - The current list of selected values
- [allEnumOptions=[]]: EnumOptionsType<S>[] - The list of all the known enumOptions
Returns
- EnumOptionsType<S>["value"][]: The updated list of selected enum values with
valueadded to it in the proper location
enumOptionsValueForIndex<S extends StrictRJSFSchema = RJSFSchema>()
Returns the value(s) from allEnumOptions at the index(es) provided by valueIndex.
If valueIndex is not an array AND the index is not valid for allEnumOptions, emptyValue is returned.
If valueIndex is an array, AND it contains an invalid index, the returned array will have the resulting undefined values filtered out, leaving only valid values or in the worst case, an empty array.
Parameters
- valueIndex: string | number | Array<string | number> - The index(es) of the value(s) that should be returned
- [allEnumOptions=[]]: EnumOptionsType<S>[] - The list of all the known enumOptions
- [emptyValue]: EnumOptionsType<S>["value"] | undefined - The value to return when the non-array
valueIndexdoes not refer to a real option
Returns
- EnumOptionsType<S>["value"] | EnumOptionsType<S>["value"][] | undefined: The single or list of values specified by the single or list of indexes if they are valid. Otherwise,
emptyValueor an empty list.
enumOptionValueDecoder<S extends StrictRJSFSchema = RJSFSchema>()
Decodes a string from a DOM value attribute back to a typed enum value.
When format is 'realValue', does a reverse lookup: finds the enum option whose String(value) matches the input string and returns the original typed value.
For object/array values that were encoded as indices, falls back to index resolution.
When format is 'indexed' (the default), uses index-based resolution via enumOptionsValueForIndex.
Parameters
- value: string | string[] - The string value(s) from the DOM
- enumOptions: EnumOptionsType<S>[] | undefined - The available enum options
- [format='indexed']: OptionValueFormat - How the values were encoded on the DOM
- emptyValue: unknown - The value to return for empty/missing selections
Returns
- unknown: The original typed enum value(s)
enumOptionValueEncoder()
Encodes an enum option value into a string for a DOM value attribute.
When format is 'realValue', primitive values are converted via String().
Non-primitive values (objects, arrays) fall back to the index since String() would produce "[object Object]".
When format is 'indexed' (the default), returns the index as a string.
Parameters
- value: unknown - The typed enum value
- index: number - The option's position in the enumOptions array
- [format='indexed']: OptionValueFormat - How to encode the value for the DOM attribute
Returns
- string: The string to use as the DOM value attribute
logUnsupportedDefaultForEnum<S extends StrictRJSFSchema = RJSFSchema>()
Logs a warning when a single-select enum widget has a schema default that is not one of its enum options. Multi-select widgets are ignored because they do not use the same single-value default handling.
Parameters
- id: string - The field id used in the warning message
- schema: S - The schema whose default value is checked
- [enumOptions]: EnumOptionsType<S>[] - The enum options available to the widget
- [multiple=false]: boolean - Whether the widget allows multiple selections
errorId()
Return a consistent id for the field error element.
Parameters
- id: FieldPathId | string - Either simple string id or an FieldPathId from which to extract it
Returns
- string: The consistent id for the field error element from the given
id
examplesId()
Return a consistent id for the field examples element.
Parameters
- id: FieldPathId | string - Either simple string id or an FieldPathId from which to extract it
Returns
- string: The consistent id for the field examples element from the given
id
findSchemaDefinition<S extends StrictRJSFSchema = RJSFSchema>()
Given the name of a $ref from within a schema, using the rootSchema, look up and return the sub-schema using the path provided by that reference.
If # is not the first character of the reference, or the path does not exist in the schema, then throw an Error.
Otherwise, return the sub-schema. Also deals with nested $refs in the sub-schema.
Parameters
- $ref: string - The ref string for which the schema definition is desired
- [rootSchema=]: S - The root schema in which to search for the definition
Returns
- S: The sub-schema within the
rootSchemawhich matches the$refif it exists
Throws
- Error indicating that no schema for that reference exists
getByPath<R = unknown>()
Gets the value at path of obj, returning defaultValue when the resolved value is undefined.
A bare string path is a single literal key, not a dotted path; use toPath() to split a dotted path string into segments first.
Every segment must be an own property, matching hasByPath(), so the two can be used as a guard/read pair.
Inherited members are never resolved: getByPath({}, 'toString') returns defaultValue rather than Function.prototype.toString. For the plain form data and schemas RJSF navigates, an inherited member is never data, and the own-property rule also makes prototype internals such as __proto__ unreachable unless they are genuine own data keys.
An empty segment list resolves to nothing, so defaultValue is returned rather than obj itself; this matches hasByPath(), which is false for an empty path.
The value at a runtime-computed path cannot be known statically, so R is the caller's declaration of the expected type (like Map.get()); it defaults to unknown, which forces narrowing when no type is given.
Parameters
- obj: unknown - The object to query
- path: ObjectPath - The single key or list of path segments at which to get the value
- [defaultValue]: R - The value returned when the resolved value is
undefined
Returns
- R: The resolved value, otherwise
defaultValue
Example
getByPath({ a: { b: 1 } }, ['a', 'b']); // 1
getByPath({ 'a.b': 1 }, 'a.b'); // 1, a bare string is one literal key
getByPath({ a: { b: 1 } }, toPath('a.b')); // 1
getByPath({ a: {} }, ['a', 'missing'], 'fallback'); // 'fallback'
getByPath({}, 'toString', 'fallback'); // 'fallback', inherited members are not read
getByPath({ a: 1 }, [], 'fallback'); // 'fallback', an empty path resolves to nothing
getChangedFields(a: unknown, b: unknown, deep?: boolean)
Compares two objects and returns the names of the fields that have changed.
This function iterates over each field of object a, using _.isEqual to compare the field value with the corresponding field value in object b.
If the values are different, the field name will be included in the returned array.
When deep is true, a field holding a nested object or a same-length array is descended into and the dotted path of the deepest field that changed is returned instead of the name of the top-level field holding it.
A key that contains a . or a [ is descended into like any other: the path it produces cannot be told apart from a path through nested keys, and neither can the entry an ErrorSchema keeps for it, since toErrorSchema() spells such a name out as a path in the same way.
Parameters
- a: unknown - The first object, representing the original data to compare.
- b: unknown - The second object, representing the updated data to compare.
- [deep=false]: boolean - Optional flag that, when true, returns the dotted path of the deepest field that changed.
Returns
- string[] : An array of field names that have changed.
Example
const a = { name: 'John', age: 30 };
const b = { name: 'John', age: 31 };
const changedFields = getChangedFields(a, b);
console.log(changedFields); // Output: ['age']
Example (deep)
const a = { items: [{ qux: '', corge: '' }] };
const b = { items: [{ qux: 'a', corge: '' }] };
console.log(getChangedFields(a, b)); // Output: ['items']
console.log(getChangedFields(a, b, true)); // Output: ['items.0.qux']
getDecimalSeparator(languages?: string | string[])
Determines the locale-specific decimal separator. It uses the provided locale or the first locale in navigator.languages (if available) and falls back to "en".
Parameters
- languages?: string | string[] - Optional array of locales or a single locale string.
Returns
- string : The decimal separator character (typically '.' or ',').
Example
const separator = getDecimalSeparator('fr');
console.log(separator); // Output: ','
getDiscriminatorFieldFromSchema<S extends StrictRJSFSchema = RJSFSchema>()
Returns the discriminator.propertyName when defined in the schema if it is a string. A warning is generated when it is not a string.
Returns undefined when a valid discriminator is not present.
Parameters
- schema: S - The schema from which the discriminator is potentially obtained
Returns
- string | undefined: The
discriminator.propertyNameif it exists in the schema, otherwiseundefined
getDateElementProps()
Given date & time information with optional yearRange & format, returns props for DateElement
Parameters
- date: DateObject - Object containing date with optional time information
- time: boolean - Determines whether to include time or not
- [yearRange=[1900, new Date().getFullYear() + 2]]: [number, number] - Controls the list of years to be displayed
- [format='YMD']: DateElementFormat - Controls the order in which day, month and year input element will be displayed
Returns
- Array of props for DateElement
getInputProps<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>()
Using the schema, defaultType and options, extract out the props for the <input> element that make sense.
Parameters
- schema: S - The schema for the field provided by the widget
- [defaultType]: string | undefined - The default type, if any, for the field provided by the widget
- [options=]: UIOptionsType<T, S, F> - The UI Options for the field provided by the widget
- [autoDefaultStepAny=true]: boolean - Determines whether to auto-default step=any when the type is number and no step
Returns
- InputPropsType: The extracted
InputPropsTypeobject
getOptionMatchingSimpleDiscriminator()
Compares the value of discriminatorField within formData against the value of discriminatorField within schema for each option. Returns index of first option whose discriminator matches formData. Returns undefined if there is no match.
This function does not work with discriminators of "type": "object" and "type": "array"
Parameters
- [formData]: T | undefined - The current formData, if any, used to figure out a match
- options: S[] - The list of options to find a matching options from
- [discriminatorField]: string | undefined - The optional name of the field within the options object whose value is used to determine which option is selected
Returns
- number | undefined: index of the matched option
getOptionValueFormat()
Resolves the effective optionValueFormat for enum-backed widgets.
Provides a single source of truth for the default DOM encoding format ('indexed') used by SelectWidget, RadioWidget, and CheckboxesWidget.
Widgets should call this helper once and pass the result to enumOptionValueEncoder, enumOptionValueDecoder, and enumOptionSelectedValue rather than reading options.optionValueFormat directly.
Parameters
- [options]: { optionValueFormat?: OptionValueFormat } | undefined - The widget options (typically from the
optionsprop, already resolved fromui:optionsandui:globalOptions)
Returns
- OptionValueFormat: The resolved
OptionValueFormat, defaulting to'indexed'when not set
getPropertySchema<S extends StrictRJSFSchema = RJSFSchema>()
Returns the sub-schema declared for property in the properties of schema, falling back to an empty schema when the schema has no such property.
Callers treat the properties of a schema as schemas of the same type S, which the JSONSchema7 typing of properties cannot express, so this function owns that single assertion rather than repeating it at every lookup.
Parameters
- schema: S | undefined - The schema, if any, from which to read the property sub-schema
- property: string - The name of the property whose sub-schema is desired
Returns
- S: The sub-schema for
property, or an empty schema when it is not declared
getSchemaType()
Gets the type of a given schema.
If the type is not explicitly defined, then an attempt is made to infer it from other elements of the schema as follows:
- schema.const: Returns the
guessType()of that value - schema.enum: Returns
string - schema.properties: Returns
object - schema.additionalProperties: Returns
object - schema.patternProperties: Returns
object - type is an array with a length of 2 and one type is 'null': Returns the other type
Parameters
- schema: S - The schema for which to get the type
Returns
- string | string[] | undefined: The type of the schema
getSubmitButtonOptions<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>()
Extracts any ui:submitButtonOptions from the uiSchema and merges them onto the DEFAULT_OPTIONS
Parameters
- [uiSchema=]: UiSchema<T, S, F> - the UI Schema from which to extract submit button props
Returns
- UISchemaSubmitButtonOptions: The merging of the
DEFAULT_OPTIONSwith any custom ones