informel nested fields
by juliendelort
HTML
<script src="https://unpkg.com/informel"></script>
<div id="results">
</div>
<inform-el >
<form>
<label>
First name
<inform-field>
<input type="text" name="users[0].name.first" required />
</inform-field>
</label>
<label>
Last name
<inform-field>
<input type="text" name="users[0].name.last" required />
</inform-field>
</label>
<label>
Admin
<inform-field>
<input type="checkbox" name="users[0].admin" checked/>
</inform-field>
</label>
<label>
First name
<inform-field>
<input type="text" name="users[1].name.first" required />
</inform-field>
</label>
<label>
Last name
<inform-field>
<input type="text" name="users[1].name.last" required />
</inform-field>
</label>
<label>
Admin
<inform-field>
<input type="checkbox" name="users[1].admin" />
</inform-field>
</label>
<button type="submit">Submit</button>
</form>
</inform-el>
CSS
inform-el {
--error-margin: 5px 0 0 0;
}
inform-field[error] > input {
border: 1px solid red;
}
label {
width: 400px;
display: block;
overflow: hidden;
margin-bottom: 20px;
}
body {
background: #f6f8fa;
font-family: arial;
padding: 20px;
}
#results {
margin-bottom: 20px;
padding: 10px;
background: lightgrey;
border-radius: 5px;
white-space: pre;
font-family: monospace;
font=size: 14px;
}
JavaScript
const informEl = document.querySelector('inform-el');
const results = document.querySelector('#results');
reportResults(informEl.values);
informEl.validationHandler = ({
values
}) => {
if (values.users[0].name.first === ' ') {
return {
'values.users[0].name.first': 'No blank values!'
}
}
};
informEl.addEventListener('inform-input', ({
detail: {
values,
changedField
}
}) => {
reportResults(values, changedField)
});
function reportResults(values, changedField) {
results.textContent = JSON.stringify({
values,
changedField: changedField || '',
dirty: informEl.dirty
}, null, '\t');
}