Planning an advanced form builder
The user wants an advanced form builder in Vue.js that includes dynamic field generation and validation. I should provide code and explanations, possibly using the Composition API with a dynamic schema. I’ll focus on main concepts like form schema, validation rules, and the component to render. I can also incorporate field types like text, select, checkbox, and date. The user didn't specify details, but I should ensure the output captures both the builder aspect and the dynamic rendering capabilities.Designing the FormBuilder component
I should focus on dynamic field generation and validation in the FormBuilder component. It will take in a schema and render accordingly, with a UI for adding fields through controls like "Add Field." I’ll use a reactive array for fields where each has properties like id, label, type, model, options, and validation rules. Additionally, I might show how to create a custom validator or use Vuelidate. The code will rely on Vue 3's Composition API with the <script setup> structure, ensuring everything is clear and well-designed.Implementing a validation engine
For a self-contained code solution, I can create a light validation engine. Each field will have an array of rules, either as functions or references to built-in validators. Upon submission, I'll run the validators for each field and set an error object keyed by the field's id. User interaction is essential, so I'll allow dynamic field generation where users can add new fields through the UI.
I’ll design a data model with types like 'text', 'textarea', 'select', 'checkbox', and 'number.' The schema will include a reactive array of field definitions to manage form data dynamically.Designing field validation and builder UI
For each field, I’ll create an array of validator functions based on its properties, running those validators on each value. I can implement features like onBlur validation or a validateAll function on submit. I want to incorporate dynamic additions in the builder UI, allowing users to select field types, input labels and placeholders, and set options.
The user can add or remove fields and possibly reorder them. Since they wanted an "advanced form builder," I’ll provide a simplified architecture rather than long code blocks. I'll focus on designing a top-level FormBuilder.vue component that manages schema editing and passes it to a DynamicForm.vue component.Implementing field handling and submission
In the implementation, I’ll set up maxLength and pattern for fields. For select types, I'll handle option parsing with a simple split operation to create label-value pairs. Once configured, I’ll push the base field into the fields array and reset the builder field.
I also want to include a function to remove fields by index. On submission, I’ll capture the data and trigger a console log or alert. The template will display an "Add field" form on the left, current fields listed below, and dynamically call <DynamicForm :schema="fields" @submit="handleFormSubmit" />. I’ll keep styling in mind for clarity. Below is a self‑contained example of an “advanced” dynamic form builder in Vue 3 that supports:
- A builder UI to add/remove fields at runtime.
- A reusable DynamicForm component that:
- Renders fields from a schema.
- Manages form state with
v-model-like behavior.
- Performs dynamic validation based on field definitions.
- Emits validated data on submit.
You can adapt or extend this to your needs (more field types, custom validators, etc.).
1. Core dynamic form renderer – DynamicForm.vue
<!-- src/components/DynamicForm.vue -->
<template>
<form @submit.prevent="handleSubmit" class="dynamic-form">
<div
v-for="field in schema"
:key="field.id || field.key"
class="form-field"
>
<label :for="field.key" class="form-label">
{{ field.label }}
<span v-if="field.required" class="required">*</span>
</label>
<!-- TEXT / TEXTAREA / NUMBER -->
<input
v-if="field.type === 'text' || field.type === 'number'"
:id="field.key"
:type="field.type"
v-model="formData[field.key]"
:placeholder="field.placeholder || ''"
class="form-input"
@blur="validateField(field)"
/>
<textarea
v-else-if="field.type === 'textarea'"
:id="field.key"
v-model="formData[field.key]"
:placeholder="field.placeholder || ''"
class="form-textarea"
@blur="validateField(field)"
/>
<!-- SELECT -->
<select
v-else-if="field.type === 'select'"
:id="field.key"
v-model="formData[field.key]"
class="form-select"
@blur="validateField(field)"
>
<option value="" disabled>
{{ field.placeholder || 'Select an option' }}
</option>
<option
v-for="opt in field.options || []"
:key="opt.value"
:value="opt.value"
>
{{ opt.label }}
</option>
</select>
<!-- CHECKBOX -->
<div v-else-if="field.type === 'checkbox'" class="checkbox-wrapper">
<input
:id="field.key"
type="checkbox"
v-model="formData[field.key]"
class="form-checkbox"
@blur="validateField(field)"
/>
<span class="checkbox-label">
{{ field.checkboxLabel || field.placeholder || field.label }}
</span>
</div>
<!-- FALLBACK (text) -->
<input
v-else
:id="field.key"
type="text"
v-model="formData[field.key]"
:placeholder="field.placeholder || ''"
class="form-input"
@blur="validateField(field)"
/>
<!-- Validation error -->
<p v-if="errors[field.key]" class="error-message">
{{ errors[field.key] }}
</p>
</div>
<button type="submit" class="submit-button">
Submit
</button>
</form>
</template>
<script setup>
import { reactive, watch, computed } from 'vue'
/**
* Expected schema item shape (example):
* {
* id: 'uniq-1',
* key: 'firstName',
* label: 'First Name',
* type: 'text' | 'textarea' | 'select' | 'checkbox' | 'number',
* placeholder: 'Enter first name',
* required: true,
* minLength: 2,
* maxLength: 50,
* pattern: '^[A-Za-z]+$',
* options: [ { label: 'A', value: 'a' }, ... ] // for select
* min: 0, // for number
* max: 100 // for number
* }
*/
const props = defineProps({
schema: {
type: Array,
required: true,
default: () => [],
},
})
const emit = defineEmits(['submit', 'validation-state'])
const formData = reactive({})
const errors = reactive({})
// Initialize / sync formData when schema changes
watch(
() => props.schema,
(newSchema) => {
const existingKeys = Object.keys(formData)
// Add or initialize keys for new fields
newSchema.forEach((field) => {
if (!field.key) return
if (!Object.prototype.hasOwnProperty.call(formData, field.key)) {
formData[field.key] = getDefaultValue(field)
}
})
// Remove data for fields no longer present
existingKeys.forEach((key) => {
const stillExists = newSchema.some((f) => f.key === key)
if (!stillExists) {
delete formData[key]
delete errors[key]
}
})
},
{ immediate: true, deep: true }
)
const isValid = computed(() => {
return Object.values(errors).every((e) => !e)
})
function getDefaultValue(field) {
if (field.type === 'checkbox') return false
if (field.type === 'number') return null
return ''
}
function validateField(field) {
const value = formData[field.key]
const error = getFieldError(field, value)
errors[field.key] = error
emit('validation-state', { isValid: !error && isValid.value, errors })
return !error
}
function validateAll() {
let allValid = true
props.schema.forEach((field) => {
if (!validateField(field)) {
allValid = false
}
})
return allValid
}
function getFieldError(field, value) {
// Handle required
if (field.required) {
const isEmpty =
value === null ||
value === undefined ||
value === '' ||
(Array.isArray(value) && value.length === 0) ||
(field.type === 'checkbox' && !value)
if (isEmpty) {
return `${field.label} is required`
}
}
// String-based rules
if (
typeof value === 'string' &&
value !== '' &&
(field.minLength || field.maxLength || field.pattern)
) {
if (field.minLength && value.length < field.minLength) {
return `${field.label} must be at least ${field.minLength} characters`
}
if (field.maxLength && value.length > field.maxLength) {
return `${field.label} must be at most ${field.maxLength} characters`
}
if (field.pattern) {
try {
const reg = new RegExp(field.pattern)
if (!reg.test(value)) {
return `${field.label} has an invalid format`
}
} catch (e) {
// Invalid regex: ignore pattern rule
}
}
}
// Number-based rules
if (field.type === 'number' && value !== null && value !== '') {
const num = Number(value)
if (Number.isNaN(num)) {
return `${field.label} must be a number`
}
if (field.min !== undefined && num < field.min) {
return `${field.label} must be at least ${field.min}`
}
if (field.max !== undefined && num > field.max) {
return `${field.label} must be at most ${field.max}`
}
}
return ''
}
function handleSubmit() {
const ok = validateAll()
emit('validation-state', { isValid: ok, errors })
if (ok) {
// Emit a shallow copy so parent can't accidentally mutate internal state
emit('submit', { ...formData })
}
}
</script>
<style scoped>
.dynamic-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.form-field {
display: flex;
flex-direction: column;
}
.form-label {
font-weight: 600;
margin-bottom: 0.25rem;
}
.required {
color: #e11d48;
margin-left: 0.25rem;
}
.form-input,
.form-textarea,
.form-select {
border: 1px solid #d4d4d8;
border-radius: 4px;
padding: 0.4rem 0.5rem;
font-size: 0.9rem;
}
.form-textarea {
min-height: 60px;
resize: vertical;
}
.checkbox-wrapper {
display: flex;
align-items: center;
gap: 0.5rem;
}
.checkbox-label {
font-size: 0.9rem;
}
.form-checkbox {
width: 16px;
height: 16px;
}
.error-message {
color: #dc2626;
font-size: 0.8rem;
margin-top: 0.2rem;
}
.submit-button {
align-self: flex-start;
padding: 0.5rem 1.2rem;
border-radius: 4px;
border: none;
cursor: pointer;
background: #2563eb;
color: white;
font-weight: 600;
font-size: 0.9rem;
}
.submit-button:hover {
background: #1d4ed8;
}
</style>
2. Form builder UI – FormBuilder.vue
This component lets you dynamically configure fields and previews them using DynamicForm.vue.
<!-- src/components/FormBuilder.vue -->
<template>
<div class="builder-layout">
<!-- Builder Panel -->
<section class="builder-panel">
<h2>Form Builder</h2>
<div class="builder-form">
<div class="builder-row">
<label>
Label
<input v-model="builderField.label" type="text" />
</label>
<label>
Key (model name)
<input v-model="builderField.key" type="text" />
</label>
</div>
<div class="builder-row">
<label>
Type
<select v-model="builderField.type">
<option value="text">Text</option>
<option value="textarea">Textarea</option>
<option value="number">Number</option>
<option value="select">Select</option>
<option value="checkbox">Checkbox</option>
</select>
</label>
<label>
Placeholder
<input v-model="builderField.placeholder" type="text" />
</label>
</div>
<div class="builder-row">
<label class="inline">
<input v-model="builderField.required" type="checkbox" />
Required
</label>
<label v-if="builderField.type !== 'checkbox'">
Min length
<input v-model.number="builderField.minLength" type="number" />
</label>
<label v-if="builderField.type !== 'checkbox'">
Max length
<input v-model.number="builderField.maxLength" type="number" />
</label>
</div>
<div class="builder-row" v-if="builderField.type === 'number'">
<label>
Min value
<input v-model.number="builderField.min" type="number" />
</label>
<label>
Max value
<input v-model.number="builderField.max" type="number" />
</label>
</div>
<div class="builder-row" v-if="builderField.type !== 'checkbox'">
<label>
Pattern (RegExp)
<input
v-model="builderField.pattern"
type="text"
placeholder="e.g. ^[A-Za-z]+$"
/>
</label>
</div>
<div
class="builder-row"
v-if="builderField.type === 'select'"
>
<label>
Options
<textarea
v-model="builderField.optionsText"
placeholder="One option per line, e.g.:
Label 1|value1
Label 2|value2
"
/>
</label>
</div>
<button @click="addField" class="add-button">
Add field
</button>
</div>
<div v-if="fields.length" class="current-fields">
<h3>Current fields</h3>
<ul>
<li v-for="(f, index) in fields" :key="f.id">
<span class="field-chip">
{{ f.label }} ({{ f.type }}) – key: "{{ f.key }}"
<span v-if="f.required" class="field-required">required</span>
</span>
<button
@click="removeField(index)"
class="remove-field"
>
✕
</button>
</li>
</ul>
</div>
</section>
<!-- Preview / Runtime Form -->
<section class="preview-panel">
<h2>Form Preview / Runtime</h2>
<p v-if="!fields.length" class="empty-message">
Add some fields to see the form preview here.
</p>
<DynamicForm
v-else
:schema="fields"
@submit="handleSubmit"
@validation-state="handleValidationState"
/>
<div v-if="lastSubmit" class="result-panel">
<h3>Last submitted data</h3>
<pre>{{ lastSubmit }}</pre>
</div>
</section>
</div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import DynamicForm from './DynamicForm.vue'
const fields = ref([])
const builderField = reactive({
label: '',
key: '',
type: 'text',
placeholder: '',
required: false,
minLength: null,
maxLength: null,
min: null,
max: null,
pattern: '',
optionsText: '',
})
const lastSubmit = ref(null)
function resetBuilderField() {
builderField.label = ''
builderField.key = ''
builderField.type = 'text'
builderField.placeholder = ''
builderField.required = false
builderField.minLength = null
builderField.maxLength = null
builderField.min = null
builderField.max = null
builderField.pattern = ''
builderField.optionsText = ''
}
function addField() {
if (!builderField.label.trim() || !builderField.key.trim()) {
alert('Label and key are required for a field.')
return
}
const key = builderField.key.trim()
const keyExists = fields.value.some((f) => f.key === key)
if (keyExists) {
alert(`Field key "${key}" already exists. Please choose another key.`)
return
}
const field = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2),
label: builderField.label.trim(),
key,
type: builderField.type,
placeholder: builderField.placeholder || '',
required: builderField.required,
minLength: builderField.minLength || null,
maxLength: builderField.maxLength || null,
min:
builderField.type === 'number' && builderField.min !== null
? builderField.min
: undefined,
max:
builderField.type === 'number' && builderField.max !== null
? builderField.max
: undefined,
pattern: builderField.pattern || '',
}
if (builderField.type === 'select') {
const options = builderField.optionsText
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((line) => {
const [label, value] = line.split('|').map((s) => s.trim())
return {
label: label || value,
value: value || label,
}
})
field.options = options
}
fields.value.push(field)
resetBuilderField()
}
function removeField(index) {
fields.value.splice(index, 1)
}
function handleSubmit(data) {
// In a real app you would send `data` to an API or use it in some way
lastSubmit.value = JSON.stringify(data, null, 2)
}
function handleValidationState(payload) {
// payload = { isValid, errors }
// Example: track validity; here we simply log it
// console.log('validation state changed:', payload)
}
</script>
<style scoped>
.builder-layout {
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1.7fr);
gap: 2rem;
align-items: flex-start;
padding: 1.5rem;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
sans-serif;
font-size: 14px;
}
section {
background: #fafafa;
border-radius: 8px;
border: 1px solid #e5e7eb;
padding: 1rem 1.25rem;
}
h2 {
font-size: 1.1rem;
margin-bottom: 0.75rem;
}
h3 {
font-size: 1rem;
margin: 0.5rem 0;
}
.builder-panel {
display: flex;
flex-direction: column;
gap: 1rem;
}
.builder-form {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.builder-row {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.builder-row label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.85rem;
flex: 1 1 45%;
}
.builder-row input,
.builder-row select,
.builder-row textarea {
border: 1px solid #d4d4d8;
border-radius: 4px;
padding: 0.3rem 0.4rem;
font-size: 0.85rem;
}
.builder-row textarea {
min-height: 60px;
resize: vertical;
}
label.inline {
flex-direction: row;
align-items: center;
gap: 0.4rem;
margin-top: 1.1rem;
}
.add-button {
margin-top: 0.5rem;
align-self: flex-start;
padding: 0.4rem 0.9rem;
border-radius: 4px;
border: none;
background: #22c55e;
color: white;
cursor: pointer;
font-size: 0.85rem;
font-weight: 600;
}
.add-button:hover {
background: #16a34a;
}
.current-fields ul {
list-style: none;
padding: 0;
margin: 0.25rem 0 0;
}
.current-fields li {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 0.25rem;
}
.field-chip {
background: #eef2ff;
border-radius: 999px;
padding: 0.15rem 0.6rem;
font-size: 0.8rem;
}
.field-required {
margin-left: 0.4rem;
color: #dc2626;
font-size: 0.75rem;
}
.remove-field {
border: none;
background: transparent;
color: #b91c1c;
font-size: 0.9rem;
cursor: pointer;
padding: 0 0.3rem;
}
.preview-panel {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.empty-message {
font-size: 0.85rem;
color: #6b7280;
}
.result-panel {
margin-top: 0.5rem;
background: #f9fafb;
border-radius: 6px;
padding: 0.5rem;
border: 1px dashed #d1d5db;
}
.result-panel pre {
font-size: 0.8rem;
overflow-x: auto;
margin: 0;
}
</style>
3. Mounting the builder – App.vue and main.js
App.vue:
<template>
<FormBuilder />
</template>
<script setup>
import FormBuilder from './components/FormBuilder.vue'
</script>
main.js (Vue 3 + Vite default style):
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
4. How to extend
- Add more field types: date pickers, radio groups, file uploads, etc.
- Add more validation rules: custom validator functions on the schema (e.g.
customRules: [(value) => value === 'foo' || 'Must be foo']).
- Persist schemas to a backend or localStorage.
- Allow drag‑and‑drop reordering of fields.
If you tell me your exact target (e.g. you want JSON schema compatibility, or integration with VeeValidate/Yup), I can adapt this to that specific setup.