Search code examples
javascripthtmlregexreactjshtml-input

How to restrict user input to hexadecimal value in React?


This is my input:
enter image description here

This is its definition:

<Input
  // type="number"
  id="numeroSerie"
  name="num_serie"
  defaultValue={this.state.num_serie}
  onChange={this.onChange}
  required
  pattern="[a-fA-F0-9]+"
  maxlength="1"
/>;

Using pattern="[a-fA-F0-9]+" means that the user can enter whatever he wants and then the validation will be performed when he clicks on the form submit button.
What I would like is:

When the user clicks on any letter or a number that isn't hexadecimal, the input value would not change. Just like when the input type is number, and the user tries to enter a text.

Is this possible to implement?


Solution

  • To avoid illegal input (the input value would not change):

    Add a regex condition inside the handler function would be fine.

    /^[0-9a-f]+$/.test(yourValue) // hexadecimal
    

    const {useState} = React;
    
    const App = () => {
      const [value, setValue] = useState("");
      const onChange = e => {
        const input = e.currentTarget.value;
        if (/^[0-9a-f]+$/.test(input) || input === "") {
          setValue(input);
        }
      };
      return (
        <div className="App">
          <input
            id="numeroSerie"
            name="num_serie"
            value={value}
            onChange={onChange}
          />
        </div>
      );
    }
    ReactDOM.render(<App />, document.getElementById("root"));
        <div id="root"></div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>