Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function formToData(form) {
const formData = new FormData(form.get()[0])
var params = new Map()
var errors = []
var inputElements = {}
// Initially iterate through all the inputs
form.find(':input').each(function(key, value) {
var elem = $(this)
var name = elem.attr('name')
if (name !== undefined) {
inputElements[name] = elem
var emptyValue = elem.data('empty')
if (emptyValue !== undefined) {
params[name] = emptyValue
}
}
})
// Now iterate through all the supplied form values
for (let [paramKey, paramValue] of formData.entries()) {
let inputElement = inputElements[paramKey]
let dataType = inputElement.data('type')
try {
if (!inputElement[0].checkValidity()) {
// Invalid inputs return paramValue of '',
// so we need to differentiate between that
// and an actually empty input
throw Error()
} else if (dataType === 'integer') {
if (!paramValue) {
params[paramKey] = null
} else {
if (paramValue.includes('.')) {
throw Error()
}
paramValue = parseInt(paramValue)
if (paramValue != paramValue) {
throw Error()
}
params[paramKey] = paramValue
}
} else if (dataType === 'number') {
if (!paramValue) {
params[paramKey] = null
} else {
paramValue = parseFloat(paramValue)
if (paramValue != paramValue) {
throw Error()
}
params[paramKey] = paramValue
}
} else if (dataType === 'boolean') {
params[paramKey] = true
} else if (dataType === 'array') {
if (inputElement.is('select')) {
params[paramKey] = params[paramKey].concat([paramValue])
} else {
params[paramKey] = JSON.parse(paramValue)
}
} else if (dataType === 'object') {
params[paramKey] = JSON.parse(paramValue)
} else {
params[paramKey] = paramValue
}
} catch(e) {
errors.push(paramKey)
}
}
return params
}
@youngershen

This comment has been minimized.

Copy link

commented May 4, 2017

nice work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.