4
\$\begingroup\$

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.25 and 100,000.25 -> 100000.25

  • Replacing 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)
    }
})
\$\endgroup\$
1
\$\begingroup\$

Don't guess!

You should not attempt to correct client input unless you make sure that the client knows (via a click) that a change has been made.

Converting a value like 100,1.0 to 1001.0 is a guess. The client may have intended only the 100, or the 1.0 and your guess may not be noticed.

You can vet input as it is entered or on paste, removing non numeric characters (which you don't do) eg "a100a" will become 100, but when there is ambiguity like "a100a00" it should be considered not a number.

If the result is not a number use standard validation warnings rather than guessing.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.