0

I would like to allow numbers higher than 0 in an input field of a react app - javascript. I don't want to have 0 only if it's the first letter. For example 1, 5, 15, 20, 500, 1000005 would be allowed, but 0.5 not. I found this Regex online, however it blocks ALL 0's from being entered.

  const [val, setVal] = useState("");
  return (
    <div className="App">
      <input
        value={val}
        onChange={(e) => setVal(e.target.value.replace(/[^1-9]/g, ""))}
      />
    </div>
  );
2
  • 1
    use can use condition for this , which would be best case in my opinion Commented Sep 27, 2022 at 15:07
  • 1
    Simply add a ^ in front: /^[^1-9]/. Commented Sep 27, 2022 at 15:12

2 Answers 2

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

export function App(props) {
 const [val, setVal] = useState("");
 return (
   <div className="App">
   <input
    value={val}
    onChange={(e) => {
      e.target.value>=1 ? setVal(e.target.value): setVal("")
    }}
    />
  </div>
 );
}

it will only set value greater then 0

Sign up to request clarification or add additional context in comments.

2 Comments

This allows 0.5, which it should not as per OP
Just replace the condition with greater than or equal to 1
0

To enforce integers greater than 0 you can remove all non-digits, followed by removing leading zeros:

  const [val, setVal] = useState("");
  return (
    <div className="App">
      <input
        value={val}
        onChange={(e) => setVal(e.target.value.replace(/[^0-9]/g, '').replace(/^0+/, ''))}
      />
    </div>
  );

Comments

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.