user3348410
user3348410

Reputation: 2833

How format currency with javascript and validate

i'm using react and wan't to format and validate input value.

my use cases are:

1- in input will enable writing only digits and dot [.] 2- value can be max 1000 3- if user will write eg:

if 200 it will be 200.00

if 99 it will be 99.00

if 10000 it will be 1000.00

if 22222 it will be 222.22

and i need to prevent writing two dot there need to be only one dot and before last value.

what i try?

onKeyPress function:

onKeyPress={e => {
            const BIRTHNUMBER_ALLOWED_CHARS_REGEXP = /^[0-9.]*$/;
            if (!BIRTHNUMBER_ALLOWED_CHARS_REGEXP.test(e.key)) {

              e.preventDefault();
            }
          }}

with this way i prevent any characters except dot and digit. But with another use cases i don't know how figure out

Upvotes: 1

Views: 714

Answers (1)

ehab
ehab

Reputation: 8034

It is always better to delegate validation to specific libraries, like Yup or some other library out there.

Your problem can be broken into two problems: validating and then formatting.

You can easily validate that a string is a float. a float contains only digits and a dot (maximum one).

const isAFloat = str => str.split('').filter(char => char !== '.').every(char => !Number.isNaN(parseInt(char))) && 
str.indexOf('.') === str.lastIndexOf('.')

to format the float you can then do, this will give you the format you wanted

parseFloat(str,10).toFixed(2)

Upvotes: 1

Related Questions