Hello developers, in this blog we are going to learn how to add number format validation in react js
First of all, you need to create an app using the following command :
npx create-react-app react-number-format
Then install react number format in your app using the following command :
npm i react-number-format
After that make a component and paste the following code :
import { Typography } from '@mui/material'; import { Box } from '@mui/system'; import React from 'react' import NumberFormat from 'react-number-format'; const App = () => { const limit = (val, max) => { if (val.length === 1 && val[0] > max[0]) { val = '0' + val; } if (val.length === 2) { if (Number(val) === 0) { val = '01'; //this can happen when user paste number } else if (val > max) { val = max; } } return val; } const cardExpiry = (val) => { let month = limit(val.substring(0, 2), '12'); let date = limit(val.substring(2, 4), '31'); return month + (date.length ? '/' + date : ''); } return ( <div> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Currency Format :</Typography> <NumberFormat thousandSeparator={true} prefix={"$"} id='numberformat' /> </Box> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Credit Card Format :</Typography> <NumberFormat format="#### #### #### ####" id='numberformat' /> </Box> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Currency Format with Custom separator :</Typography> <NumberFormat thousandSeparator={'.'} prefix={"$"} decimalScale={2} decimalSeparator={','} id='numberformat' /> </Box> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Credit Card Format With Mask :</Typography> <NumberFormat format={'#### #### #### ####'} mask='-' id='numberformat' /> </Box> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Custom Format Method Credit Card :</Typography> <NumberFormat format={cardExpiry} id='numberformat' /> </Box> <Box display='flex' flexDirection='column' > <Typography variant="p" color="initial" py={2} fontWeight='bold'>Phone Number Format :</Typography> <NumberFormat format="+91 #####-#####" mask="_" id='numberformat' /> </Box> </div> ) } export default App
Demo:
There are lots of customizations available you can try it :
https://github.com/s-yadav/react-number-format
I hope this article is helpful for you 🙂