最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to allow only Decimal values up to 2 decimal places in an input field in React JS - Stack Overflow

programmeradmin4浏览0评论

I have an Input field to which I want user to be able to enter only number/decimal values up to 2 decimal places. User should not be able to enter any alphabet. Can someone please help me with this

My React Component:

import React from 'react'
import { useState } from "react";

function LoanCalc() {
    const [amount, setAmount] = useState();

     const handleChange = (event) => {
         
     }

  return (
    <div className="Container">
      <div className="LoanAmount">
        <label>Loan Amount:</label>
        <span>$
          <input type="text" min="4000" max="100000" value={amount} onChange={handleChange}/>
        </span>
      </div>
    </div>
  );
 }
export default LoanCalc

I have an Input field to which I want user to be able to enter only number/decimal values up to 2 decimal places. User should not be able to enter any alphabet. Can someone please help me with this

My React Component:

import React from 'react'
import { useState } from "react";

function LoanCalc() {
    const [amount, setAmount] = useState();

     const handleChange = (event) => {
         
     }

  return (
    <div className="Container">
      <div className="LoanAmount">
        <label>Loan Amount:</label>
        <span>$
          <input type="text" min="4000" max="100000" value={amount} onChange={handleChange}/>
        </span>
      </div>
    </div>
  );
 }
export default LoanCalc
Share Improve this question asked Mar 10, 2022 at 15:48 Red CloudRed Cloud 1294 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

I've created a code example on codepen.io, too. This is the link to codepen

https://codepen.io/dns_nx/pen/mdxZPaL

In my example, you can only enter up to 2 decimal values. It does not matter, if you use , or . as splitter for the decimals.

This is the code:

import React from 'react'
import { useState } from "react";

function MyComponent(props) {
  const [currentValue, setCurrentValue] = useState(undefined);
  
  function checkValue(event) {
      setCurrentValue(handleDecimalsOnValue(event.target.value));
  }
  
  function handleDecimalsOnValue(value) {
      const regex = /([0-9]*[\.|\,]{0,1}[0-9]{0,2})/s;
      return value.match(regex)[0];
  }
  
  return (
    <div>
      <input 
          type="text"
          value={currentValue}
          onChange={(event) => checkValue(event, 'change')}
      />
    </div>
  );
}

I did an update on the code above. Now using a regex expression to validate the input instead of splitting the string.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论