packages/docs/versioned_docs/version-5.24.10/api-reference/utility-functions.md
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.
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.
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.
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.
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.
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.
examplesId into the listaria-describedBy attributeAttempts 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.
value converted to a number when appropriate, otherwise the valueChecks 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.
Given a formData object, recursively creates a FormValidation error handling structure around it
FormValidation object based on the formData structureGiven 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.
DataUrl potentially containing name and raw data to be converted to a BlobReturns 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.
start and stopstart and stop aren't both <= 0 or > 0Implements a deep equals using the lodash.isEqualWith function, that provides a customized comparator that assumes all functions are equivalent.
a and b are deeply equal, false otherwiseReturn a consistent id for the field description element.
idTranslates 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.
stringToTranslate: TranslatableString - The TranslatableString value to convert to english
[params]: string[] - The optional list of replaceable parameter values to substitute to the english string
stringToTranslate itself with any replaceable parameter values substitutedRemoves 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.
selected list with the value removed from itReturns 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.
value in allEnumOptions, if not multiple. Otherwise, the list of indexes for (each of) the value(s) in value.Determines whether the given value is (one of) the selected value(s).
value is one of the selected ones, false otherwiseAdd the value to the list of selected values in the proper order as defined by allEnumOptions.
value added to it in the proper locationReturns 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.
valueIndex does not refer to a real optionemptyValue or an empty list.Return a consistent id for the field error element.
idReturn a consistent id for the field examples element.
idGiven 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.
rootSchema which matches the $ref if it existsCompares 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.
const a = { name: 'John', age: 30 };
const b = { name: 'John', age: 31 };
const changedFields = getChangedFields(a, b);
console.log(changedFields); // Output: ['age']
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.
discriminator.propertyName if it exists in the schema, otherwise undefinedGiven date & time information with optional yearRange & format, returns props for DateElement
Using the schema, defaultType and options, extract out the props for the <input> element that make sense.
InputPropsType objectCompares 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"
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:
guessType() of that valuestringobjectobjectExtracts any ui:submitButtonOptions from the uiSchema and merges them onto the DEFAULT_OPTIONS
DEFAULT_OPTIONS with any custom onesGet all passed options from ui:options, and ui:<optionName>, returning them in an object with the ui: stripped off.
Any globalOptions will always be returned, unless they are overridden by options in the uiSchema.
ui:xxx optionsxxx optionsui:xxx options with the ui: stripped off along with all globalOptionsReturns the template with the given name from either the uiSchema if it is defined or from the registry
otherwise. NOTE, since ButtonTemplates are not overridden in uiSchema only those in the registry are returned.
TemplatesTypeRegistry from which to read the templateUIOptionsType from which to read an alternate templateuiSchema or registry for the nameGiven a schema representing a field to render and either the name or actual Widget implementation, returns the
React component that is used to render the widget. If the widget is already a React component, then it is wrapped
with a MergedWidget. Otherwise an attempt is made to look up the widget inside of the registeredWidgets map based
on the schema type and widget name. If no widget component can be found an Error is thrown.
Widget implementation to useWidget implementationWidget component to useWidget component that can be returnedGiven a specific value attempts to guess the type of a schema element. In the case where we have to implicitly
create a schema, it is useful to know what type to use based on the data we are defining.
Stringifies the schema and returns the hash of the resulting string.
Detects whether the widget exists for the schema with the associated registryWidgets and returns true if it does, or false if it doesn't.
Widget implementation to useWidget implementationReturn a consistent id for the field help element.
idThis function checks if the given schema matches a single constant value.
This happens when either the schema has an enum array with a single value or there is a const defined.
schema has a single constant value, false otherwiseChecks to see if the uiSchema contains the widget field and that the widget is not hidden
uiSchema describes a custom widget, false otherwiseDetects whether the given schema contains fixed items.
This is the case when schema.items is a non-empty array that only contains objects.
Determines whether a thing is an object for the purposes of RSJF.
In this case, thing is an object if it has the type object but is NOT null, an array or a File.
Helper function that will return the value to use for a widget label based on hideLabel.
The fallback is used as the return value from the function when hideLabel is true.
Due to the implementation of theme components, it may be necessary to return something other than undefined to cause the theme component to not render a label.
Some themes require may false and others may require an empty string.
[label]: string | ReactElement | undefined - The label string or component to render when not hidden
[hideLabel]: boolean| undefined - Flag, if true, will cause the label to be hidden
[fallback]: undefined | false | '' - One of 3 values, undefined (the default), false or an empty string
string | boolean | undefined: fallback if hideLabel is true, otherwise label
Converts a local Date string into a UTC date string
Date() constructordateString is truthy, otherwise undefinedMerges the defaults object of type T into the formData of type T
When merging defaults and form data, we want to merge in this specific way:
mergeExtraArrayDefaults is true, in which case the extras are appended onto the end of the form dataRecursively merge deeply nested objects.
@returns - A new object that is the merge of the two given objects
Recursively merge deeply nested schemas. The difference between mergeSchemas and mergeObjects is that mergeSchemas only concats arrays for values under the 'required' keyword, and when it does, it doesn't include duplicate values. NOTE: Uses shallow comparison for the duplicate checking.
Return a consistent id for the optionIndexs of a Radio or Checkboxes widget
idGets the list of options from the schema. If the schema has an enum list, then those enum values are returned.
The labels for the options will be extracted from the non-standard, RJSF-deprecated enumNames if it exists, otherwise
the label will be the same as the value. If the schema has a oneOf or anyOf, then the value is the list of
const values from the schema and the label is either the schema.title or the value. If a uiSchema is provided
and it has the ui:enumNames matched with enum or it has an associated oneOf or anyOf with a list of objects
containing ui:title then the UI schema values will replace the values from the schema.
NOTE: enumNames is deprecated and will be removed in a future major version of RJSF. Use the "ui:enumNames" property in the uiSchema instead.
Given a list of properties and an order list, returns a list that contains the properties ordered correctly.
If order is not an array, then the untouched properties list is returned.
Otherwise properties is ordered per the order list.
If order contains a '_' then any properties that are not mentioned explicity in order will be places in the location of the _.
properties orderedReturns a string representation of the num that is padded with leading "0"s if necessary
widthParses the dateString into a DateObject, including the time information when includeTime is true
DateObjectExtracts the range spec information { step?: number, min?: number, max?: number } that can be spread onto an HTML input from the range analog in the schema { multipleOf?: number, minimum?: number, maximum?: number }.
Potentially substitutes all replaceable parameters with the associated value(s) from the params if available.
When a params array is provided, each value in the array is used to replace any of the replaceable parameters in the inputString using the %1, %2, etc. replacement specifiers.
Check to see if a schema specifies that a value must be true. This happens when:
schema.const is truthyschema.enum == [true]schema.anyOf or schema.oneOf has a single value which recursively returns trueschema.allOf has at least one value which recursively returns trueDetermines whether the given component should be rerendered by comparing its current set of props and state against the next set.
If either of those two sets are not the same, then the component should be rerendered.
Return a consistent id for the field title element.
idReturns the constant value from the schema when it is either a single value enum or has a const key. Otherwise, throws an error.
Returns a UTC date string for the given dateObject.
If time is false, then the time portion of the string is removed.
DateObject to convert to a date stringConverts an errorSchema into a list of RJSFValidationErrors
ErrorSchema instance to convertRJSFValidationErrors extracted from the errorSchemaTransforms a RJSF validation errors list into an ErrorSchema
const changesThis = [
{ property: '.level1.level2[2].level3', message: 'err a', stack: '.level1.level2[2].level3 err a' },
{ property: '.level1.level2[2].level3', message: 'err b', stack: '.level1.level2[2].level3 err b' },
{ property: '.level1.level2[4].level3', message: 'err b', stack: '.level1.level2[4].level3 err b' },
];
const intoThis = {
level1: {
level2: {
2: { level3: { errors: ['err a', 'err b'] } },
4: { level3: { errors: ['err b'] } },
},
},
};
ErrorSchema built from the list of RJSFValidationErrorsUnwraps the errorHandler structure into the associated ErrorSchema, stripping the addError() functions from it
FormValidation error handling structureErrorSchema resulting from the stripping of the addError() functionConverts a UTC date string into a local Date format
jsonDate is falsey, otherwise a date string in local formatMerges the errors in additionalErrorSchema into the existing validationData by combining the hierarchies in the two ErrorSchemas and then appending the error list from the additionalErrorSchema obtained by calling toErrorList() on the errors in the validationData.
If no additionalErrorSchema is passed, then validationData is returned.
ValidationData into which to merge the additional errorsErrorSchemavalidationData with the additional errors from additionalErrorSchema merged into it, if provided.Recursively prefixes all $refs in a schema with the value of the ROOT_SCHEMA_PREFIX constant.
This is used in isValid to make references to the rootSchema
ROOT_SCHEMA_PREFIX is added when a $ref is part of itschemaNode with updated $refsReturns the superset of formData that includes the given set updated to include any missing fields that have computed to have defaults provided in the schema.
ValidatorType interface that will be used when necessary$refsincludeUndefinedValues as false when computing defaults for any nested object properties.Form documentation for the experimental_defaultFormStateBehavior propForm documentation for the experimental_customMergeAllOf propformData with all the defaults providedDetermines whether the combination of schema and uiSchema properties indicates that the label for the schema should be displayed in a UI.
ValidatorType interface that will be used when necessary$refsxxx optionsForm documentation for the experimental_customMergeAllOf propDetermines which of the given options provided most closely matches the formData.
Returns the index of the option that is valid and is the closest match, or 0 if there is no match.
The closest match is determined using the number of matching properties, and more heavily favors options with matching readOnly, default, or const values.
ValidatorType interface that will be used when necessary$refsForm documentation for the experimental_customMergeAllOf propformData or the selectedOption if no matchGiven the formData and list of options, attempts to find the index of the first option that matches the data.
Always returns the first option if there is nothing that matches.
ValidatorType interface that will be used when necessary$refsGiven the formData and list of options, attempts to find the index of the option that best matches the data.
Deprecated, use getFirstMatchingOption() instead.
ValidatorType interface that will be used when necessary$refsChecks to see if the schema and uiSchema combination represents an array of files
ValidatorType interface that will be used when necessary$refsForm documentation for the experimental_customMergeAllOf propChecks to see if the schema combination represents a multi-select
ValidatorType interface that will be used when necessary$refsForm documentation for the experimental_customMergeAllOf propChecks to see if the schema combination represents a select
ValidatorType interface that will be used when necessary$refsForm documentation for the experimental_customMergeAllOf propMerges the errors in additionalErrorSchema into the existing validationData by combining the hierarchies in the two ErrorSchemas and then appending the error list from the additionalErrorSchema obtained by calling validator.toErrorList() onto the errors in the validationData.
If no additionalErrorSchema is passed, then validationData is returned.
NOTE: This is function is deprecated. Use the
validationDataMerge()function exported from@rjsf/utilsinstead. This function will be removed in the next major release.
ValidatorType interface that will be used to convert an ErrorSchema to a list of errorsValidationData into which to merge the additional errorsErrorSchemavalidationData with the additional errors from additionalErrorSchema merged into it, if provided.Retrieves an expanded schema that has had all of its conditions, additional properties, references and dependencies
resolved and merged into the schema given a validator, rootSchema and rawFormData that is used to do the
potentially recursive resolution.
ValidatorType interface that will be forwarded to all the APIsForm documentation for the experimental_customMergeAllOf propSanitize the data associated with the oldSchema so it is considered appropriate for the newSchema.
If the new schema does not contain any properties, then undefined is returned to clear all the form data.
Due to the nature of schemas, this sanitization happens recursively for nested objects of data.
Also, any properties in the old schema that are non-existent in the new schema are set to undefined.
ValidatorType interface that will be used when necessaryForm documentation for the experimental_customMergeAllOf propundefined. Will return undefined if the new schema is not an object containing properties.Generates an IdSchema object for the schema, recursively
ValidatorType interface that will be used when necessaryIdSchema is desired$refsForm documentation for the experimental_customMergeAllOf propIdSchema object for the schemaGenerates an PathSchema object for the schema, recursively
ValidatorType interface that will be used when necessaryPathSchema is desired$refsForm documentation for the experimental_customMergeAllOf propPathSchema object for the schemaCreates a SchemaUtilsType interface that is based around the given validator and rootSchema parameters.
The resulting interface implementation will forward the validator and rootSchema to all the wrapped APIs.
ValidatorType interface that will be forwarded to all the APIsSchemaUtilsType interfaceThe ErrorSchemaBuilder<T> is used to build an ErrorSchema<T> since the definition of the ErrorSchema type is designed for reading information rather than writing it.
Use this class to add, replace or clear errors in an error schema by using either dotted path or an array of path names.
Once you are done building the ErrorSchema, you can get the result and/or reset all the errors back to an initial set and start again.
ErrorSchemaBuilder classReturns the ErrorSchema that has been updated by the methods of the ErrorSchemaBuilder
Usage:
import { ErrorSchemaBuilder, ErrorSchema } from "@rjsf/utils";
const builder = new ErrorSchemaBuilder();
// Do some work using the builder
...
const errorSchema: ErrorSchema = builder.ErrorSchema;
Resets all errors in the ErrorSchemaBuilder back to the initialSchema if provided, otherwise an empty set.
ErrorSchemaBuilder classAdds the errorOrList to the list of errors in the ErrorSchema at either the root level or the location within the schema described by the pathOfError.
For more information about how to specify the path see the eslint lodash plugin docs.
ErrorSchemaErrorSchema at which to add the error(s)ErrorSchemaBuilder classSets/replaces the errorOrList as the error(s) in the ErrorSchema at either the root level or the location within the schema described by the pathOfError.
For more information about how to specify the path see the eslint lodash plugin docs.
ErrorSchemaErrorSchema at which to add the error(s)ErrorSchemaBuilder classClears the error(s) in the ErrorSchema at either the root level or the location within the schema described by the pathOfError.
For more information about how to specify the path see the eslint lodash plugin docs.
ErrorSchema at which to add the error(s)ErrorSchemaBuilder class