mcgruff14
mcgruff14

Reputation: 338

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.

Upvotes: 2

Views: 2335

Answers (2)

Penny Liu
Penny Liu

Reputation: 17468

To convert half-width to full-width digits, use the string method normalize(NFKC):

const original = '1234567'
console.log(original.normalize('NFKC'))

Upvotes: 0

akky
akky

Reputation: 2907

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

Upvotes: 3

Related Questions