Advanced Dynamic Form Builder with Validation in JavaScript
Build a reusable dynamic form builder function that generates interactive forms based on a JSON schema, including custom validations and conditional field visibility.
Challenge prompt
Create a function named buildDynamicForm(schema) that accepts a JSON schema representing a form configuration and dynamically generates a HTML form. The function should render input fields, apply custom validation rules, handle conditional field visibility based on other inputs, and provide real-time validation feedback. When the form is submitted, the data should be returned as an object if all validations pass, or show appropriate error messages otherwise. The schema will include field types, labels, validation criteria (e.g., required, min/max length, regex), and dependencies for conditional display.
Guidance
- • Parse the JSON schema to dynamically create form elements including text inputs, selects, checkboxes, etc.
- • Implement validation logic that runs on input change and on form submission to provide immediate feedback.
- • Manage conditional logic to hide or show fields dynamically based on other field values using event listeners.
- • Structure your code to support extensibility for adding new field types and validation rules in the future.
Hints
- • Use event delegation or direct listeners to handle input changes for validation and conditional fields.
- • Consider maintaining a state object mapping each field's current value for easy validation and conditional checks.
- • Leverage HTML5 validation attributes where possible and supplement with custom functions for complex rules.
Starter code
function buildDynamicForm(schema) {
const form = document.createElement('form');
// Your code to dynamically build form elements
// Add validation and conditional logic
form.addEventListener('submit', (event) => {
event.preventDefault();
// Validate and gather data
// Show errors or return form data
});
return form;
}Expected output
A fully functional HTML form generated from the provided schema, that enforces validations, shows/hides fields conditionally, and returns form data as an object on successful submission.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.