Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
How can I validate this textfield where it would not allow submission if the entered value is negative?

I have this text field type number, I want to set a minimum of 0 and a text field that does not accept negative values. I was able to do that, however, once I type on it, I would not be able to delete the 0, I would first need to go at front of the 0 then type in a number, and only then would the 0 be deleted. What can I do to fix or are there more suitable ways to do this?

Codesandbox: https://codesandbox.io/s/textfield-7sfdph?file=/demo.js:127-882

Codes:

export default function BasicTextFields() {
  const [fee, setFee] = useState(0);
  const amount = parseInt(1000);
  const total = Number(amount) + Number(fee);
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(" submit");
  };
  return (
    <form onSubmit={{ handleSubmit }}>
      <TextField
        label="Fee"
        type="number"
        value={fee}
        onChange={(e) => {
          if (e.target.value === "") {
            setFee(0);
          } else {
            setFee(parseInt(e.target.value));
          }
        }}
        InputProps={{
          inputProps: {
            min: 0
          }
        }}
      />
      <button type="submit">Submit</button>
      <br />
      Total: {total}
    </form>
  );
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your onChange function is setting the value to 0 whenever the value is an empty string. When you delete something you are effectively changing the value, so the onChange function will be called.

Personally I would just call setFee with whatever value they typed because the type=number will already prevent users from typing anything that is not a number and will allow them to clear the field.

You can handle the case for when the value is empty with validation or on the onSubmit function. This is probably a better user experience.

about 4 years ago · Juan Pablo Isaza Report

0

You can check if number is negative if yes then set value to 0

const total = Number(amount) + (fee ? Number(fee) : 0);
// code 
if (Number(e.target.value) < 0) {
  setFee(0);
} else {
  setFee(parseInt(e.target.value));
}

then on submit check if value is not undefined

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!