remix-validated-form
Version:
Form component and utils for easy form validation in remix
52 lines (51 loc) • 2.09 kB
JavaScript
import * as R from "remeda";
import { getCheckboxChecked } from "./logic/getCheckboxChecked";
import { getRadioChecked } from "./logic/getRadioChecked";
const defaultValidationBehavior = {
initial: "onBlur",
whenTouched: "onChange",
whenSubmitted: "onChange",
};
export const createGetInputProps = ({ clearError, validate, defaultValue, touched, setTouched, hasBeenSubmitted, validationBehavior, name, }) => {
const validationBehaviors = {
...defaultValidationBehavior,
...validationBehavior,
};
return (props = {}) => {
const behavior = hasBeenSubmitted
? validationBehaviors.whenSubmitted
: touched
? validationBehaviors.whenTouched
: validationBehaviors.initial;
const inputProps = {
...props,
onChange: (...args) => {
var _a;
if (behavior === "onChange")
validate();
else
clearError();
return (_a = props === null || props === void 0 ? void 0 : props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, ...args);
},
onBlur: (...args) => {
var _a;
if (behavior === "onBlur")
validate();
setTouched(true);
return (_a = props === null || props === void 0 ? void 0 : props.onBlur) === null || _a === void 0 ? void 0 : _a.call(props, ...args);
},
name,
};
if (props.type === "checkbox") {
inputProps.defaultChecked = getCheckboxChecked(props.value, defaultValue);
}
else if (props.type === "radio") {
inputProps.defaultChecked = getRadioChecked(props.value, defaultValue);
}
else if (props.value === undefined) {
// We should only set the defaultValue if the input is uncontrolled.
inputProps.defaultValue = defaultValue;
}
return R.omitBy(inputProps, (value) => value === undefined);
};
};