AG_HIHI
AG_HIHI

Reputation: 1995

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?

Upvotes: 2

Views: 2399

Answers (2)

keikai
keikai

Reputation: 15146

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>

Upvotes: 2

Booboo
Booboo

Reputation: 44053

This solution uses the onkeyup event of the input element to test the content against an arbitrary regular expression. That means that the input element might momentarily display an illegal character but after the regex test reveals the content to be illegal, the prior contents will be restored. Using the onkeyup event greatly simplifies processing.

function setupField(field, re)
{
    field.autocomplete = "off";
    field.saveValue = field.value;
    field.onkeyup = function() {
        var v = field.value;
        if (v === '' || re.test(v)) {
            field.saveValue = v;
        }
        else {
            field.value = field.saveValue;
        }
    };
}

setupField(document.getElementById('hex'), /^[A-Fa-f0-9]+$/);
<input type="text" id="hex" size="8">

Upvotes: 1

Related Questions