I'm working on a web form that functions with numeric inputs. I have <input type="number"> input fields and with Chrome and Firefox things work nicely since they only allow numeric data to be filled in.
However, I need to support IE11 and it does not enforce the number type when inputting data (but does when submitting data).
Since I want to make it as easy as possible for users (who often copy-paste data from different sources), I wanna sanitize the numbers both on paste as well as on submit.
Things I'm achieving here:
Replacing spaces and commas as thousand-separators (
100 000.25 -> 100000.25and100,000.25 -> 100000.25Replacing commas a decimal pointer with a dot (
100000,25 -> 100000.25)
How would you improve the code and are there some edge cases I'm forgetting?
function sanitizeValue(value) {
return value.replace(/ /g, '')
.replace(/\./g, ',')
.replace(/[,](?=.*[,])/g, "")
.replace(/,/g, '.')
}
var form = document.getElementById('form')
var inputs = document.getElementsByTagName('input')
form.onsubmit = function(event) {
Object.values(inputs).forEach(function(input) {
input.value = sanitizeValue(input.value)
})
}
Object.values(inputs).forEach(input => {
input.onpaste = ev => {
ev.preventDefault()
let pasteValue = ev.clipboardData.getData('text/plain')
ev.target.value = sanitizeValue(pasteValue)
}
})