javascriptnumberscjk

Prevent double byte numbers in form input


Doing this in vanilla javascript. When I input numbers with two-byte character into an html input, I get an error in math we're doing onscreen in javascript, resulting in a NaN.

Behind the scenes, I'm taking the input value (a digit) and mulitplying it by a price, to get a total. The total is now NaN with the two byte number. Math is fine with the one byte number.

Is there a way to prevent the input of two-byte characters and letters in javascript?

Two Byte: 1234567
One Byte: 1234567 

This is all using Japanese to get the two byte numbers.


Solution

  • You may "prevent" those full-width digits in HTML5 form by type="number", but that might not be the best solution. Some users may not understand why their full-width digits are rejected.

    Instead, you can convert them to half-width digits after receiving. It is just subtracting the difference of two character codes.

    const original = '120444284'
    const converted = original.replace(/[0-9]/g, function (s) {
      return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
    })
    document.writeln(converted)
    

    Output

    120444284