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
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:
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:
This is a good case for a custom formControl validator. Something like this
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.
You should try changing your code a bit.
And for ts file :
This should work as per your requirements. Do let me know how it goes.