skip to Main Content

I have a requirement where I have an input field. In that input field I am passing string value seperated by commas. I am storing each input value in array. I want to restrict user from entering more than 4 characters.

For example: Suppose we have this input

["mango","papaya","jackfruit"]

I want like

["mang","papa","jack"]

I want that when someone enters more than 4 character it wont allow user to enter anything thereafter. If he presses comma then he is allow to write another string value of 4 character

component.html

<input formControlName="name" (keypress)="singleElement($event)" (input)="inputName($event)">

component.ts

inputName(event){

 this.value = (<HTMLInputElement>event.target).value    
}


singleElement(event) {
 return(
 (event.charCode > 64 && event.charCode < 91) ||
 (event.charCode > 96 && event.charCode < 123) ||
 (event.charCode > 47 && event.charCode < 58) ||
 event.charCode == 44
 )}

3

Answers


  1. To achieve the above, you can use the ‘maxlenght’ attribute in your input tag

    Syntax:
    <input maxlength="number">
    Behaviour: It won’t take input values after the stated maxlenght which in your case should be 4. So, user can’t enter more than 4 characters in the input field.

    More details: https://www.w3schools.com/tags/att_input_maxlength.asp

    You can try something like the below:

    class Component {
    inputValue = '';
        constructor() {
      }
      inputHandler(event){
        if (event.key === ','){//I don't if this works you'll need to check
          const input = document.getElementById('input');
          input.maxlenght += 5; //add the lenght for the ; and new 4 characters
          input.value += ',';
        }
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <input id='input' (keypress)="inputHandler($event)" maxlenght='4' [(ngModel)]='inputValue'>

    I don’t know if this will work, you’ll need to check and play around this to find out.

    Else if you want, you can collect a 4 charactered string from the user; when they submit clear the input and ask them to enter another.

    Though, I won’t recommend the above solutions. Alternatively, you can add a note for the user about this; collect the whole input and then process it to suit your use case.

    For Example:

    const inputValue = 'mango,banana,apple';
    const elements = inputValue.split(',');
    const result = elements.map((ele)=> ele.slice(0,4));
    console.log(result);
    Login or Signup to reply.
  2. This is a good case for a custom formControl validator. Something like this

    const fixedLength: ValidatorFn = (
      control: AbstractControl,
    ): ValidationErrors | null => {
      const value: string = control.value;
      if (value.length) {
        const values = value.split(',');
        return values.some((v) => v.length > 4)
          ? { length: 'should be 4 chars max' }
          : null;
      }
      return null;
    };

    Then you attach this validator to your form control and display the error message to the user if it is detected.

    In any case, it is not a good idea to block or disable the input, what if a user copy-paste the input? You disable the submit button and display the error state letting your user correct the input.

    Login or Signup to reply.
  3. You should try changing your code a bit.

    <input formControlName="name" (input)="inputName($event)">
    

    And for ts file :

    value: string = '';
    
      inputName(event: any) {
        const inputValue = event.target.value;
        const values = inputValue.split(',');
    
        for (let i = 0; i < values.length; i++) {
          values[i] = values[i].substring(0, 4);
        }
    
        this.value = values.join(',');
      }
    

    This should work as per your requirements. Do let me know how it goes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search