formik-stepper
Version:
Get ready to take your form-building game to the next level with this revolutionary React component. With its seamless integration with the powerful Formik library, you'll be building forms faster and more efficiently than ever before. But that's not all
71 lines (70 loc) • 2.36 kB
JavaScript
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import React from "react";
/**
* Recursively retrieves the names of all valid React elements within a parent element.
*
* @param parent - The parent React node to extract names from.
* @returns An array of names of the valid React elements.
*/
var getNames = function (parent) {
var names = [];
if (React.isValidElement(parent)) {
var childrenArray = React.Children.toArray(parent.props.children);
if (parent.props.name) {
return [parent.props.name];
}
if (childrenArray.length > 0) {
childrenArray.forEach(function (child) {
var newNames = getNames(child);
names = __spreadArray(__spreadArray([], names, true), newNames, true);
});
}
}
return names;
};
/**
* Validates the current step of a Formik form.
*
* @param errors - The errors object from Formik.
* @param setTouched - The Formik setTouched function.
* @param setFieldError - The Formik setFieldError function.
* @param currentStep - The current step React element.
* @returns A boolean indicating whether the current step is valid.
*/
export var validate = function (_a) {
var errors = _a.errors, setTouched = _a.setTouched, setFieldError = _a.setFieldError, currentStep = _a.currentStep;
if (errors && Object.keys(errors).length > 0) {
var valid_1 = true;
var touchedFields_1 = {};
var names = getNames(currentStep);
names.forEach(function (nameField) {
if (errors[nameField]) {
valid_1 = false;
touchedFields_1[nameField] = errors[nameField];
}
else {
setFieldError(nameField, "");
}
});
if (valid_1) {
setTouched({});
return true;
}
else {
setTouched(touchedFields_1);
return false;
}
}
else {
setTouched({});
return true;
}
};