How to prevent user from entering spaces in an input form field in ReactJS?

Viewed 5533

I have created a component called QueryForm to be used for search functionality. I am returning in that component this:

3 Answers

You can replace the spaces to empty string while setting the value:

const onChange = (event, { newValue }) => {
  setInputValue(newValue.replace(/\s/g, ''));
};

You can just use trim

export default function App() {
  const [val, setVal] = useState();

  return (
    <div className="App">
      <input
        value={val}
        onChange={(e) => {
          setVal(e.target.value.trim());
        }}
      />
    </div>
  );
}

Codesandbox

Good answers, but they are all assuming the input is controlled. For uncontrolled forms you want to make sure the validation is made before the onChange event is triggered. A solution that works for controlled and uncontrolled forms is this:

const onKeyDown = (event) => {
  if (event.code === 'Space') event.preventDefault()
}

Below with types included

const onKeyDown = (event: KeyboardEvent): void => {
  if (event.code === 'Space') event.preventDefault()
}

If there are more needs other than reject blank spaces the condition of that "if" statement could be a regex expression or a refactorized function.

Related