Home > Back-end >  How to type unique letters only in input text box in html or react?
How to type unique letters only in input text box in html or react?

Time:05-07

I want to create an input box that allows to type only a distinct alphabet letter in the input box ( No duplicate alphabet value, ONLY ONE)

I looked up all the attributes for input box but I couldn't find one and there were no example.

Do I have to handle it within JavaScript functions? (I am using React)

<input
            className="App-Contain-Input"
            name="containedLetter"
            type={"text"}
            onChange={containedChange}
          />

CodePudding user response:

Here is how this can be done, note that we have to use onkeydown which fires when a key is being pressed, but not before it is being released (this way we can intercept and prevent the key stroke from being taken into account):

function MyInput() {

  const containedChange = (event) => {
    if (event.key.length === 1 && event.code.startsWith('Key') && event.code.length === 4 && event.target.value.indexOf(event.key) !== -1) {
      event.preventDefault()
      return false;
    }
    
    return true
  }
          
          
  return (
    <input
      id="input"
      className="App-Contain-Input"
      name="containedLetter"
      type="text"
      onkeydown={containedChange}
    />
}

CodePudding user response:

Your containedChange function can be like this:

const containedChange = (e) => {
    const value = e.target.value;
    const lastChar = value[value.length - 1];

    if (value.slice(value.length - 1, value.length).indexOf(lastChar) != -1) {
        // show error message
    }

The function checks whether the last entered character already exists in the previous value or not.

CodePudding user response:

An isogram is a word with no repeating letters. You can check this using regex

function isIsogram (str) {
    return !/(.).*\1/.test(str);
}

Or using array.some

function isIsogram(str) {
    var strArray = str.split("");
     return !strArray.some(function(el,idx,arr){
       return arr.lastIndexOf(el)!=idx;
     });
}

In react - you need to use state to reject inputs which contain repeated letters (not an Isogram). Complete example on codesandbox.

import { useState } from 'react';

export default function App() {
  const [ text, setText ] = useState('');

  function isIsogram(str) {
    var strArray = str.split("");
     return !strArray.some(function(el,idx,arr){
       return arr.lastIndexOf(el)!==idx;
     });
}

  function handleChange(e) {
    const { value } = e.target;
    console.log(isIsogram(value));
    if (value.length === 1 || isIsogram(value)) {
      setText(value);
    }
  }

  return (
    <input value={text} onChange={handleChange} />
  );
}

CodePudding user response:

A cheeky way to do it is to convert the target value to Array => Set => Array => String:

import { useState } from 'react';

export default function Home() {
    const [value, setValue] = useState('');

    return (
        <div>
            <input
                type='text'
                value={value}
                onChange={(e) => {
                    setValue(Array.from(new Set(e.target.value.split(''))).join(''));
                }}
            />
        </div>
    );
}

CodePudding user response:

Use a state to maintain the current value of the input. Then when the value changes get the last letter of the input, check that it's a letter, and if it is a letter and it isn't already in the state, update the state with the new input value.

const { useState } = React;

function Example() {

  const [ input, setInput ] = useState('');

  function handleChange(e) {
    const { value } = e.target;
    const lastChar = value.slice(-1);
    const isLetter = /[a-zA-Z]/.test(lastChar);
    if (isLetter && !input.includes(lastChar)) {
      setInput(value);
    }
  }

  function handleKeyDown(e) {
    if (e.code === 'Backspace') {
      setInput(input.slice(0, input.length - 1));
    }
  }

  return (
    <input
      value={input}
      onChange={handleChange}
      onKeyDown={handleKeyDown}
    />
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related