Morten Sæther

← Blog

Advanced Form Configuration

#12 · 20 April 2026

Multi-step forms, conditional logic, and state that survives a refresh

Basic forms handle basic collection. Real business processes are messier - they branch on what someone answered three steps ago, they touch several entities, and they take long enough that people wander off mid-way.

This is where you get to decide whether that complexity lands on the user or stays hidden. Forms that overwhelm people get abandoned; forms that adapt to the situation get finished. Same data collected either way.

Step by step

1. Design the flow before you build it

Map the whole thing on paper first:

// Example: Customer onboarding form architecture
const formFlow = {
    steps: [
        {
            id: 'contact-info',
            title: 'Contact Information',
            required: ['firstName', 'lastName', 'email', 'phone'],
            optional: ['middleName', 'preferredName'],
            nextStep: 'business-type'
        },
        {
            id: 'business-type',
            title: 'Business Information',
            required: ['businessType'],
            conditional: {
                field: 'businessType',
                values: {
                    'individual': 'individual-details',
                    'startup': 'business-details',
                    'enterprise': 'business-details'
                }
            }
        },
        {
            id: 'business-details',
            title: 'Business Details',
            required: ['companyName', 'industry', 'employeeCount'],
            optional: ['website', 'description'],
            nextStep: 'services-selection'
        },
        {
            id: 'services-selection',
            title: 'Service Selection',
            required: ['primaryService'],
            optional: ['additionalServices'],
            nextStep: 'review-submit'
        },
        {
            id: 'review-submit',
            title: 'Review and Submit',
            readonly: true,
            actions: ['submit', 'back', 'save-draft']
        }
    ]
};

Then the navigation between steps:

<!-- Multi-step form container -->
<div class="multi-step-form" data-current-step="1" data-total-steps="5">
    <!-- Progress indicator -->
    <div class="form-progress">
        <div class="progress-bar">
            <div class="progress-fill" style="width: 20%"></div>
        </div>
        <div class="step-indicators">
            <div class="step active">1</div>
            <div class="step">2</div>
            <div class="step">3</div>
            <div class="step">4</div>
            <div class="step">5</div>
        </div>
        <div class="step-description">
            <h3>Contact Information</h3>
            <p>Let's start with your basic contact details</p>
        </div>
    </div>
    
    <!-- Form steps container -->
    <div class="form-steps">
        <!-- Step 1: Contact Information -->
        <div class="form-step active" id="step-contact-info">
            <div class="step-content">
                <div class="form-grid">
                    <div class="form-group required">
                        <label for="firstName">First Name</label>
                        <input type="text" id="firstName" name="firstName" required 
                               data-validation="required,minLength:2">
                        <div class="field-error" id="firstName-error"></div>
                    </div>
                    
                    <div class="form-group required">
                        <label for="lastName">Last Name</label>
                        <input type="text" id="lastName" name="lastName" required 
                               data-validation="required,minLength:2">
                        <div class="field-error" id="lastName-error"></div>
                    </div>
                    
                    <div class="form-group required full-width">
                        <label for="email">Email Address</label>
                        <input type="email" id="email" name="email" required 
                               data-validation="required,email">
                        <div class="field-hint">We'll use this to send you important updates</div>
                        <div class="field-error" id="email-error"></div>
                    </div>
                    
                    <div class="form-group required">
                        <label for="phone">Phone Number</label>
                        <input type="tel" id="phone" name="phone" required 
                               data-validation="required,phone"
                               data-format="phone">
                        <div class="field-error" id="phone-error"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Step 2: Business Type Selection -->
        <div class="form-step" id="step-business-type">
            <div class="step-content">
                <div class="selection-cards">
                    <div class="selection-card" data-value="individual">
                        <div class="card-icon">👤</div>
                        <h4>Individual</h4>
                        <p>Personal account for individual use</p>
                        <input type="radio" name="businessType" value="individual" id="type-individual">
                    </div>
                    
                    <div class="selection-card" data-value="startup">
                        <div class="card-icon">🚀</div>
                        <h4>Startup</h4>
                        <p>Early-stage company</p>
                        <input type="radio" name="businessType" value="startup" id="type-startup">
                    </div>
                    
                    <div class="selection-card" data-value="enterprise">
                        <div class="card-icon">🏢</div>
                        <h4>Enterprise</h4>
                        <p>Established business</p>
                        <input type="radio" name="businessType" value="enterprise" id="type-enterprise">
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Form navigation -->
    <div class="form-navigation">
        <button type="button" class="btn btn-secondary" id="prev-step" disabled>
            Previous
        </button>
        <button type="button" class="btn btn-outline-secondary" id="save-draft">
            Save as Draft
        </button>
        <button type="button" class="btn btn-primary" id="next-step">
            Next Step
        </button>
    </div>
</div>

2. Conditional logic

Fields appearing and disappearing based on what someone has told you. The groups are divs with a data-group attribute, and the rules say which groups each answer shows, hides and makes required:

class ConditionalFields {
    constructor(form) {
        this.form = form;
        this.rules = {};
    }

    // A radio group is several inputs with the same name, so listen on all of them
    add(fieldName, rules) {
        this.rules[fieldName] = rules;
        this.form.querySelectorAll(`[name="${fieldName}"]`).forEach(input => {
            input.addEventListener('change', (e) => this.apply(fieldName, e.target.value));
        });
    }

    apply(fieldName, value) {
        const rule = this.rules[fieldName] && this.rules[fieldName][value];
        if (!rule) return;

        (rule.hide || []).forEach(group => this.hideGroup(group));
        (rule.show || []).forEach(group => this.showGroup(group));
        (rule.required || []).forEach(name => {
            const field = this.form.querySelector(`[name="${name}"]`);
            if (field) field.required = true;
        });
    }

    showGroup(name) {
        const group = this.form.querySelector(`[data-group="${name}"]`);
        if (!group) return;
        group.hidden = false;
        const firstInput = group.querySelector('input, select, textarea');
        if (firstInput) firstInput.focus();
    }

    // A hidden field must not stay required, and must not carry a stale value into the submit
    hideGroup(name) {
        const group = this.form.querySelector(`[data-group="${name}"]`);
        if (!group) return;
        group.hidden = true;
        group.querySelectorAll('input, select, textarea').forEach(input => {
            if (input.type === 'checkbox' || input.type === 'radio') {
                input.checked = false;
            } else {
                input.value = '';
            }
            input.required = false;
        });
    }
}

const conditional = new ConditionalFields(document.querySelector('.onboarding-steps'));

conditional.add('businessType', {
    individual: { hide: ['businessDetails'] },
    startup:    { show: ['businessDetails'], required: ['companyName', 'industry'] },
    enterprise: { show: ['businessDetails'], required: ['companyName', 'industry', 'employeeCount'] }
});

The rule of thumb: never show a field whose answer you could have worked out yourself.

3. Validation that carries its weight

class FieldValidator {
    constructor() {
        this.rules = {
            required: (value) => value.trim() !== '',
            email: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
            phone: (value) => /^\+?[1-9]\d{0,15}$/.test(value.replace(/\s/g, '')),
            minLength: (value, min) => value.length >= parseInt(min, 10),
            maxLength: (value, max) => value.length <= parseInt(max, 10),
            pattern: (value, pattern) => new RegExp(pattern).test(value)
        };

        this.messages = {
            required: 'This field is required',
            email: 'Please enter a valid email address',
            phone: 'Please enter a valid phone number',
            minLength: 'Must be at least {param} characters long',
            maxLength: 'Must be no more than {param} characters long',
            pattern: 'Please match the requested format'
        };
    }

    // Rules come from the markup: data-validation="required,minLength:2"
    validateField(field) {
        const value = field.value || '';
        const errors = [];

        (field.dataset.validation || '').split(',').forEach(rule => {
            const [name, param] = rule.split(':');
            const check = this.rules[name];
            if (!check) return;
            // An empty optional field passes everything except "required"
            if (name !== 'required' && value.trim() === '') return;
            if (!check(value, param)) {
                errors.push(this.messages[name].replace('{param}', param || ''));
            }
        });

        return { valid: errors.length === 0, errors };
    }

    // Validate while typing, with a pause so people get to finish the word
    watch(field) {
        let timer;
        field.addEventListener('input', () => {
            clearTimeout(timer);
            timer = setTimeout(() => this.showResult(field), 500);
        });
        field.addEventListener('blur', () => {
            clearTimeout(timer);
            this.showResult(field);
        });
    }

    showResult(field) {
        const result = this.validateField(field);
        const errorContainer = document.getElementById(`${field.id}-error`);

        field.classList.toggle('invalid', !result.valid);
        field.classList.toggle('valid', result.valid);
        if (errorContainer) errorContainer.textContent = result.valid ? '' : result.errors[0];
        this.showIcon(field, result.valid ? 'success' : 'error');
    }

    showIcon(field, type) {
        const wrapper = field.closest('.form-group');
        const existing = wrapper.querySelector('.validation-icon');
        if (existing) existing.remove();

        const icon = document.createElement('span');
        icon.className = `validation-icon ${type}`;
        icon.textContent = type === 'success' ? '✓' : '✗';
        wrapper.appendChild(icon);
    }
}

const validator = new FieldValidator();
document.querySelectorAll('[data-validation]').forEach(field => validator.watch(field));

Checking that an email address isn’t already registered is a server-side job, and the example leaves it out.

4. State that survives a refresh

This is the one people forget. Someone gets three steps into a form, their browser reloads, and everything’s gone - they’re not starting again.

If the form is a Power Pages multistep form, this is already handled. With Start New Session On Load set to No, which is the default, the session is kept and the person can close the page and come back to the step they were on.

For a form you build yourself, the draft is your problem. localStorage survives a refresh, but it belongs to the browser, not the user, and nothing in it expires on its own. So key the draft to the signed-in user, give it an expiry, and clear it when the form is submitted.

class FormStateManager {
    // userId comes from Liquid in the page template: {{ user.id }}
    constructor(form, userId) {
        this.form = form;
        this.storageKey = `form_state_${form.dataset.formId}_${userId}`;
        this.maxAge = 24 * 60 * 60 * 1000; // a day, then it's gone
        this.autoSaveInterval = 30000;
    }

    saveFormState(currentStep) {
        const state = {
            data: this.extractFormData(),
            currentStep: currentStep,
            savedAt: Date.now()
        };
        localStorage.setItem(this.storageKey, JSON.stringify(state));
        this.showSaveIndicator();
    }

    // Returns the saved state, or null if there is none or it has expired
    loadFormState() {
        try {
            const saved = localStorage.getItem(this.storageKey);
            if (!saved) return null;
            const state = JSON.parse(saved);
            if (Date.now() - state.savedAt > this.maxAge) {
                this.clearFormState();
                return null;
            }
            return state;
        } catch (error) {
            console.warn('Failed to load form state:', error);
            return null;
        }
    }

    // Call this on successful submit
    clearFormState() {
        localStorage.removeItem(this.storageKey);
    }

    // getCurrentStep is whatever your navigation uses to know where the user is
    setupAutoSave(getCurrentStep) {
        setInterval(() => this.saveFormState(getCurrentStep()), this.autoSaveInterval);
    }

    extractFormData() {
        const data = {};
        for (const [key, value] of new FormData(this.form).entries()) {
            if (key in data) {
                data[key] = [].concat(data[key], value);
            } else {
                data[key] = value;
            }
        }
        return data;
    }

    // Puts the values back and returns the step to navigate to
    restoreFormState(state) {
        Object.entries(state.data).forEach(([name, value]) => {
            const values = [].concat(value);
            this.form.querySelectorAll(`[name="${name}"]`).forEach(field => {
                if (field.type === 'checkbox' || field.type === 'radio') {
                    field.checked = values.includes(field.value);
                } else {
                    field.value = values[0];
                }
            });
        });
        return state.currentStep;
    }

    showSaveIndicator() {
        const indicator = document.getElementById('save-indicator');
        if (!indicator) return;
        indicator.classList.add('visible');
        setTimeout(() => indicator.classList.remove('visible'), 2000);
    }
}

Restoring a radio value doesn’t fire change, so after restoreFormState call conditional.apply('businessType', value) yourself for the groups to show up again.

5. Writing to more than one entity

The Web API creates one record per call and returns its ID in the entityid response header. Every call carries the anti-forgery token from shell.getTokenDeferred(), lookups are set with @odata.bind on the navigation property rather than a raw GUID, and each table needs Web API site settings plus a table permission for the web role doing the writing.

function getToken() {
    return new Promise((resolve, reject) => {
        shell.getTokenDeferred().done(resolve).fail(reject);
    });
}

async function createRecord(entitySet, data) {
    const response = await fetch(`/_api/${entitySet}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            '__RequestVerificationToken': await getToken()
        },
        body: JSON.stringify(data)
    });
    if (!response.ok) throw new Error(`${entitySet}: ${response.status}`);
    return response.headers.get('entityid');
}

async function submitOnboarding(data) {
    const contactId = await createRecord('contacts', {
        firstname: data.firstName,
        lastname: data.lastName,
        emailaddress1: data.email,
        telephone1: data.phone
    });

    let accountId = null;
    if (data.businessType !== 'individual') {
        accountId = await createRecord('accounts', {
            name: data.companyName,
            websiteurl: data.website,
            'primarycontactid@odata.bind': `/contacts(${contactId})`
        });
    }

    // Customer is a polymorphic lookup: bind the account if there is one, else the contact
    const customer = accountId
        ? { 'customerid_account@odata.bind': `/accounts(${accountId})` }
        : { 'customerid_contact@odata.bind': `/contacts(${contactId})` };

    const caseId = await createRecord('incidents', {
        title: `Service request - ${data.primaryService}`,
        description: data.description,
        caseorigincode: 3, // Web
        ...customer
    });

    return { contactId, accountId, caseId };
}

Three calls, three records, and no transaction across them. If the case fails, the contact and the account already exist. Decide up front whether that’s acceptable, or whether the failure path deletes what the earlier calls created.

What this looks like in practice

The TechStart Solutions customer onboarding form:

<!-- Customer Onboarding Form HTML Structure -->
<div class="advanced-onboarding-form" id="customer-onboarding">
    <!-- Progress indicator -->
    <div class="progress-container">
        <div class="progress-steps">
            <div class="progress-step active" data-step="1">
                <span class="step-number">1</span>
                <span class="step-label">Contact</span>
            </div>
            <div class="progress-step" data-step="2">
                <span class="step-number">2</span>
                <span class="step-label">Business</span>
            </div>
            <div class="progress-step" data-step="3">
                <span class="step-number">3</span>
                <span class="step-label">Services</span>
            </div>
            <div class="progress-step" data-step="4">
                <span class="step-number">4</span>
                <span class="step-label">Review</span>
            </div>
        </div>
        <div class="progress-bar">
            <div class="progress-fill" style="width: 25%"></div>
        </div>
    </div>
    
    <!-- Form steps -->
    <form class="onboarding-steps" data-form-id="customer-onboarding">
        <!-- Step 1: Contact Information -->
        <div class="form-step active" id="step-1">
            <h2>Let's get to know you</h2>
            <p>Please provide your contact information to get started.</p>
            
            <div class="form-grid two-column">
                <div class="form-group required">
                    <label for="firstName">First Name</label>
                    <input type="text" id="firstName" name="firstName" required 
                           data-validation="required,minLength:2"
                           placeholder="Enter your first name">
                    <div class="field-error" id="firstName-error"></div>
                </div>
                
                <div class="form-group required">
                    <label for="lastName">Last Name</label>
                    <input type="text" id="lastName" name="lastName" required 
                           data-validation="required,minLength:2"
                           placeholder="Enter your last name">
                    <div class="field-error" id="lastName-error"></div>
                </div>
                
                <div class="form-group required full-width">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" required 
                           data-validation="required,email"
                           placeholder="your.email@example.com">
                    <div class="field-hint">We'll use this for important updates about your account</div>
                    <div class="field-error" id="email-error"></div>
                </div>
                
                <div class="form-group required">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone" required 
                           data-validation="required,phone"
                           data-format="phone"
                           placeholder="(555) 123-4567">
                    <div class="field-error" id="phone-error"></div>
                </div>
                
                <div class="form-group">
                    <label for="preferredContact">Preferred Contact Method</label>
                    <select id="preferredContact" name="preferredContact">
                        <option value="email">Email</option>
                        <option value="phone">Phone</option>
                        <option value="text">Text Message</option>
                    </select>
                </div>
            </div>
        </div>
        
        <!-- Step 2: Business Type -->
        <div class="form-step" id="step-2">
            <h2>Tell us about your business</h2>
            <p>This helps us customize our services for your specific needs.</p>
            
            <div class="business-type-selector">
                <div class="type-option" data-type="individual">
                    <input type="radio" name="businessType" value="individual" id="individual">
                    <label for="individual">
                        <div class="option-icon">👤</div>
                        <h4>Individual</h4>
                        <p>Personal projects and individual consulting</p>
                    </label>
                </div>
                
                <div class="type-option" data-type="startup">
                    <input type="radio" name="businessType" value="startup" id="startup">
                    <label for="startup">
                        <div class="option-icon">🚀</div>
                        <h4>Startup</h4>
                        <p>Early-stage company looking to build or scale</p>
                    </label>
                </div>
                
                <div class="type-option" data-type="enterprise">
                    <input type="radio" name="businessType" value="enterprise" id="enterprise">
                    <label for="enterprise">
                        <div class="option-icon">🏢</div>
                        <h4>Enterprise</h4>
                        <p>Established business with complex requirements</p>
                    </label>
                </div>
            </div>
            
            <!-- Conditional business details -->
            <div class="conditional-fields" data-group="businessDetails" hidden>
                <div class="form-grid two-column">
                    <div class="form-group required">
                        <label for="companyName">Company Name</label>
                        <input type="text" id="companyName" name="companyName" 
                               data-validation="required,minLength:2"
                               placeholder="Your Company Name">
                        <div class="field-error" id="companyName-error"></div>
                    </div>
                    
                    <div class="form-group">
                        <label for="website">Website</label>
                        <input type="url" id="website" name="website" 
                               placeholder="https://www.yourcompany.com">
                    </div>
                    
                    <div class="form-group required">
                        <label for="industry">Industry</label>
                        <select id="industry" name="industry" data-validation="required">
                            <option value="">Select your industry</option>
                            <option value="technology">Technology</option>
                            <option value="healthcare">Healthcare</option>
                            <option value="finance">Finance</option>
                            <option value="retail">Retail</option>
                            <option value="manufacturing">Manufacturing</option>
                            <option value="other">Other</option>
                        </select>
                        <div class="field-error" id="industry-error"></div>
                    </div>
                    
                    <div class="form-group">
                        <label for="employeeCount">Number of Employees</label>
                        <select id="employeeCount" name="employeeCount">
                            <option value="">Select range</option>
                            <option value="1-10">1-10</option>
                            <option value="11-50">11-50</option>
                            <option value="51-200">51-200</option>
                            <option value="201-1000">201-1000</option>
                            <option value="1000+">1000+</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </form>
    
    <!-- Navigation buttons -->
    <div class="form-navigation">
        <button type="button" class="btn btn-secondary" id="prev-btn" disabled>
            ← Previous
        </button>
        
        <div class="nav-center">
            <button type="button" class="btn btn-outline" id="save-draft-btn">
                💾 Save Draft
            </button>
            <span class="save-indicator" id="save-indicator">Draft saved</span>
        </div>
        
        <button type="button" class="btn btn-primary" id="next-btn">
            Next →
        </button>
    </div>
</div>

And the styling that holds it together:

/* Advanced Form Styling */
.advanced-onboarding-form {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.progress-container {
    margin-bottom: 3rem;
}

.progress-steps {
    display: flex;
    justify-content: space-between;
    margin-bottom: 1rem;
}

.progress-step {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    flex: 1;
}

.progress-step::after {
    content: '';
    position: absolute;
    top: 15px;
    left: 50%;
    width: 100%;
    height: 2px;
    background: #e9ecef;
    z-index: -1;
}

.progress-step:last-child::after {
    display: none;
}

.progress-step.active .step-number,
.progress-step.completed .step-number {
    background: var(--primary-color);
    color: white;
}

.progress-step.active::after,
.progress-step.completed::after {
    background: var(--primary-color);
}

.step-number {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #e9ecef;
    color: #6c757d;
    font-weight: 600;
    margin-bottom: 0.5rem;
    transition: all 0.3s ease;
}

.step-label {
    font-size: 0.875rem;
    color: #6c757d;
    font-weight: 500;
}

.business-type-selector {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.type-option {
    position: relative;
}

/* Hide the radio visually but keep it in the tab order and for screen readers */
.type-option input[type="radio"] {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip: rect(0 0 0 0);
    white-space: nowrap;
}

.type-option input[type="radio"]:focus-visible + label {
    outline: 3px solid var(--primary-color);
    outline-offset: 2px;
}

.type-option label {
    display: block;
    padding: 1.5rem;
    border: 2px solid #e9ecef;
    border-radius: 12px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;
}

.type-option label:hover {
    border-color: var(--primary-color);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 102, 204, 0.15);
}

.type-option input[type="radio"]:checked + label {
    border-color: var(--primary-color);
    background: linear-gradient(135deg, var(--primary-color) 0%, #0056b3 100%);
    color: white;
}

.option-icon {
    font-size: 2rem;
    margin-bottom: 1rem;
}

.conditional-fields {
    margin-top: 2rem;
    padding-top: 2rem;
    border-top: 1px solid #e9ecef;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.form-navigation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 3rem;
    padding-top: 2rem;
    border-top: 1px solid #e9ecef;
}

.nav-center {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.save-indicator {
    font-size: 0.875rem;
    color: var(--success-color);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.save-indicator.visible {
    opacity: 1;
}

Wrapping up

Multi-step workflows, conditional logic, validation and state management turn a painful process into one people get through. Progressive disclosure, feedback at every step, and data that doesn’t evaporate.

Test every conditional path, including the odd combinations - that’s where these break. And check it on a phone, since long forms are what people abandon on mobile.

Next: file uploads and attachments, so people can send you documents without emailing them.