Skip to content

Instantly share code, notes, and snippets.

@tomchristie
Created January 14, 2017 19:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomchristie/d55b55e0b5c77f685f48cb0687a52f7a to your computer and use it in GitHub Desktop.
Save tomchristie/d55b55e0b5c77f685f48cb0687a52f7a to your computer and use it in GitHub Desktop.
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
Copy link

nice work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment