dev_O
dev_O

Reputation: 163

How can I prevent certain characters from being deleted from a React input tag?

I would like to know how to prevent a specific string from being erased even if I press backspace from the input passed the value.

product : [none_fix]changeValue

I want to prevent the [none_fix] part from being erased even if I press backspace.

Upvotes: 2

Views: 1318

Answers (2)

Abhishek Satyam
Abhishek Satyam

Reputation: 41

You can write plane javascript in this, this will work for you. This will work even with multiple entries of your "[none_fix]". Suppose here we don't want to remove '_' even after user press backspace or delete this.

Below 3 cases can be possible for deletion.

The user presses backspace and deletes the char before the cursor, The user presses canc and deletes the char after the cursor, The user selects the text and presses backspace or canc and deletes the selected text

    const textDom = document.getElementById('desiredId');
  if (textDom) {
    textDom.addEventListener('keydown', (e) => {
      let allowClear = true;
      const start = textDom.selectionStart;
          const end = textDom.selectionEnd;
          const { value } = textDom;
          const key = e.keyCode;
          if (key === 8 && value[start - 1] === '_') allowClear = false;
      if (key === 46 && value[start] === '_') allowClear = false;
      if ((key === 8 || key === 46) && value.substring(start, end).indexOf('_') !== -1) allowClear = false;
      if (allowClear === false) {
        console.error('Editing certain characters not allowed);
        e.preventDefault();
      }
    }, false);

Upvotes: 0

millhouse
millhouse

Reputation: 10007

By making your input a Controlled Component, you can decide what value the input displays. Put whatever logic you need in the input's onChange handler - so in this case, don't propagate changes that would result in the UNERASABLE_TEXT being deleted:


const UNERASEABLE_TEXT = "[none_fix]";

export default function App() {
  const [controlledValue, setControlledValue] = useState(UNERASEABLE_TEXT);

  const onInputChanged = (e) => {
    const newValue = e.target.value;
    // Only allow changes that retain the magic string:
    if (newValue.startsWith(UNERASEABLE_TEXT)) {
      setControlledValue(newValue);
    }
  };

  return <input onChange={onInputChanged} value={controlledValue} />;
}


Upvotes: 5

Related Questions