Search code examples
htmlcssreactjsinputsemantic-ui-react

Limitted character input


I'm trying to create input limitted to only 4 characters using reactjs semantic ui, I have tried a lot of ways of doing that but none of them seems to work.

<Input fluid
  value={this.state.code}
  type="text"
  minlength="4" maxlength="8" size="10"
  placeholder={t('Code')}
  onChange={this.onCodeChange.bind(this)}
  error={this.state.formErrorsKeys.code}
/>

Also I'm thinking if it's possible to make an input splitted into 4 input areas.

Cheers!


Solution

  • All you need is to add custom validation function which takes the input value and returns modified string.

    Something like this:

    const validateField = string => {
        return string.slice(0, 4);
    };
    
    console.log(validateField('string')); // => 'stri'
    console.log(validateField('test_test')); // => 'test'

    Here is an example: https://codesandbox.io/s/r55228449p

    UPD

    Also I'm thinking if it's possible to make an input splitted into 4 input areas

    Updated the example to add something similar to "an input splitted into 4 input areas"