0

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    

1 Answer 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.
Sign up to request clarification or add additional context in comments.

3 Comments

this works but still needs back up validations in the backend as html attributes/element can be removed using inspect elements
In case the user have altered the html attribute, generally the frontend should send the data to the server and the backend server should handle the validation. In case the data is not valid, server can send BAD_REQUEST as response.
Note that, this kind of validation should not be done by the frontend, since there would be repetation of code Frontend-Web, Android, iOS, Windows App, Mac App, Linux App. So, in case you need to update the custom validation, you have to update all the applications. Hence generally it is recommended that the validation should be done at single place only i.e. backend server. At the server, you can try to parseInt the user provided value and accept/reject the API request based on data validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.