score:0
here's one approach,
const validation_map = dynamic_forms.reduce((acc, current) => {
current.inputs?.foreach((input) => {
acc[input.name] = input.validation;
});
return acc;
}, {});
const validate = (input, validation) => {
const inputlength = input.length;
const { required, minlength, maxlength } = validation;
return (
(required && !inputlength) ||
(!isnan(minlength) && inputlength < minlength) ||
(!isnan(maxlength) && inputlength > maxlength)
);
};
export default function app() {
const [formvalues, setformvalues] = usestate({});
const updateformvalue = (name, value) => {
setformvalues((prev) => ({ ...prev, [name]: value }));
};
const handleinputchange = (event) => {
const { name, value } = event.target;
updateformvalue(name, { value });
};
const handlesubmit = () => {
setformvalues((prev) => {
const updatedvalues = { ...prev };
object.entries(validation_map).foreach(([name, validation]) => {
const input = formvalues[name]?.value || "";
updatedvalues[name] = {
value: input,
hasvalidationerror: validate(input, validation)
};
});
return updatedvalues;
});
};
const handleinputblur = (event) => {
const { name, value } = event.target;
updateformvalue(name, {
value,
hasvalidationerror: validate(value, validation_map[name])
});
};
return (
<div>
<form autocomplete="off">
{dynamic_forms.map((item) => (
<div key={item.texts.header}>
<h3>{item.texts.header}</h3>
{item.inputs && (
<>
{item.inputs.map((eachinput) => {
const { label, name, type, validation, error } = eachinput;
const { value, hasvalidationerror } = formvalues[name] || {};
return (
<div key={label}>
<label>{label}</label>
<input
style={{
border: hasvalidationerror ? "1px red solid" : "solid"
}}
{...validation}
type={type}
onblur={handleinputblur}
value={value || ""}
name={name}
onchange={handleinputchange}
/>
{hasvalidationerror && (
<div style={{ color: "red" }}>{error}</div>
)}
</div>
);
})}
</>
)}
</div>
))}
<button onclick={handlesubmit}>submit</button>
</form>
</div>
);
}
i did not quite understand the error field for each input, isn't it supposed to be different for each validation? for example, if the password is not provided error can be "password is required", but if it's provided and it does not meet the min length requirement then the error should be something like "password should have minimum x characters". since only a generic error message is given for each input, i have only displayed that in case of a validation error. if you want to show different messages for different cases, instead of having the boolean hasvalidationerror
in state ,you can use a string errormessage
and have the function validate
return the required error message
Source: stackoverflow.com
Related Query
- Creating dynamic forms and its validation react
- React - How to handle nested forms and its value
- Creating image and simultaneously displaying its dimensions in React
- React Creating Dynamic Select and Option Elements with Material-UI
- Creating a dynamic button in React and Redux
- Creating a dynamic header UI with React and Material UI
- Creating dynamic radio buttons with React and Meteor and Simple Schema (using pup boilerplate)
- Form validation with react and material-ui
- What's useEffect execution order and its internal clean-up logic in react hooks?
- Async validation with Formik, Yup and React
- How to create forms with React and Rails?
- React with MVC data annotations and unobtrusive validation
- React table dynamic page size but with size limit and pagination
- Creating 'Div' and 'Span' Components in React Native
- Dynamic column and values in react table
- How do I use React and forms to get an array of checked checkbox values?
- React routing between static and dynamic pages
- React Bootstrap and React.PropTypes validation function
- Django - DRF (django-rest-framework-social-oauth2) and React creating a user
- React Router v4 components with similar paths (fixed and dynamic path param) are "overlapping"
- Typing redux forms v7 with TypeScript and React
- Disable autofill forms with React and Material UI
- React Native - flex, ScrollView and dynamic height not filling screen
- Formik React with 2 buttons (Submit and Save) to submit form - Save button not to trigger validation
- React router path validation and redirection
- Creating a Custom Button in React Typescript and add onClick Event
- React Router 4 and exact path with dynamic param
- Dynamic Import and Lazy load React Components
- Modelling Dynamic Forms as React Component
- React Jest creating error "new Error('...')" exit and fail testing immediately
More Query from same tag
- How to verify a text field with api value in react js.?
- How to stop react re-rendering component, if part of the state changes?
- Uncaught Invariant Violation: Maximum update depth exceeded
- clear(); method not working for React inputs
- How to update state of parent from child component in reactJS
- React router doesn't work (Maybe a conflict with Babel)
- How do I set Image src using url in React?
- Dynamic children navigation in React.js (propagating events and properties)
- Converting functional component to class component
- React-Router-Redux dispatched LOCATION_CHANGE twice, remove search value
- How to update data in reducer state in react
- react how to change Navbar dynamically when you are logged in
- Form does not have data in FormData javascript
- changing font size of material-ui buttons, and having the buttons scale?
- How to solve a problem with Array.sort Cannot assign to read only property '0' of object
- New data array of objects in D3 join is not being recognized correctly
- Material-UI absolute positioning inside a Grid
- css modules reference keyframe name inside jsx
- Stuck trying to fetch data from MongoDB into Gatsby using `gatsby-source-mongodb`
- Cannot pass object data to modal
- How to put props.children in JSX tag
- add new data inside redux state tree
- Why are most of the components in this app being updated every second?
- Babel not transpile files from parent dir
- Reset component into modal
- how to send props from a Component to Redux FieldArray
- How can you show a modal in react when you press the back button browser?
- event.target.name is undefined
- How can I display both of JSX elements in the same row without one or another?
- Apollo Client 3 evict query result - doesn't work?