@undermuz/use-form
Version:
React library for build forms
70 lines (69 loc) • 2.05 kB
JavaScript
// src/useForm/middlewares/validate.ts
import { FORM_ACTIONS } from "../reducer.js";
var getFormErrors = (state) => {
const { tests, touched, values } = state;
const errors = {};
for (let index = 0; index < tests.length; index++) {
const [names, testList, errorText = "Invalid"] = tests[index];
for (const name of names) {
if (!touched.includes(name)) {
continue;
}
for (const valueTest of testList) {
if (valueTest(values[name], values)) {
continue;
}
if (!errors[name]) {
errors[name] = [];
}
const fieldErrors = errors[name];
fieldErrors.push(errorText);
break;
}
}
}
return errors;
};
var getValidateFunction = (action, store) => {
const { validate: customValidate = null } = action.payload;
const state = store.getState();
return customValidate != null ? customValidate : state.validate;
};
var validateEffect = (action, store, settings = {}) => {
const { silent = false, checkOnlyFilled = true } = action;
const { debug = false } = settings;
const triggers = [
FORM_ACTIONS.SET_VALUE,
FORM_ACTIONS.SET_VALUES,
FORM_ACTIONS.SET_TESTS,
FORM_ACTIONS.SET_TOUCHED_FIELD,
FORM_ACTIONS.SET_TOUCHED,
FORM_ACTIONS.SET_FIELDS,
FORM_ACTIONS.SET_VALIDATE,
FORM_ACTIONS.VALIDATE_FORM
];
if (!triggers.some((t) => action.type === t) || silent) {
return;
}
const state = store.getState();
const validate = getValidateFunction(action, store);
const validatedTouched = checkOnlyFilled ? state.touched : Object.keys(state.fields);
const validateState = {
...state,
touched: validatedTouched
};
const newErrors = validate(validateState, debug);
store.dispatch({
type: FORM_ACTIONS.SET_ERRORS,
payload: { errors: newErrors }
});
};
var createValidating = (settings = {}) => (store) => (next) => (action) => {
const result = next(action);
validateEffect(action, store, settings);
return result;
};
export {
createValidating,
getFormErrors
};