'How to add Validations to my Input Field in React JS

I have a Input field to which I want to add validations. The conditions should be that amount cannot be 0 and should not enter any characters.

My React Code:

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

function LoanInput() {

  const [loanAmount, setLoanAmount] = useState(0);

  const handleValidation = (e) => { 
    const formattedValue = (Number(e.target.value.replace(/\D/g, '')) || 0).toLocaleString();   
    setLoanAmount(formattedValue);
  }


  return (
    <div className="LoanAmountInput">
      <div className="LoanAmount">
        <label>Loan Amount</label>
        <input type="text" value={loanAmount} onChange={handleValidation} />
        <span style={{ color: "red" }}></span>
      </div>
    </div>
  );
}

export default LoanInput    


Solution 1:[1]

Actually, you can use the default validation provided by the browser using the input type. In your case, your code would be as follow:

<input type="number" min="1" value={loanAmount} />

Why this approach?

  • The browser takes care of the validation and input sanitization.
  • For mobile/tablet devices, it will show only numpad keyboard to the user for data input.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashok