Created
January 14, 2017 19:22
-
-
Save tomchristie/d55b55e0b5c77f685f48cb0687a52f7a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice work