I have an input textbox field where a user can enter comma separated values like...
value 1,value 2,value 3,value 4
I have a requirement to set the maximum length of each value entered in that field to be 128 characters. I know we have a maxlength
property which will set at overall field level. But is there any way which I can restrict the length of each value that is being entered in the field?
<input type="text" formControlName="licenseOwnerName" maxlength="128">
Above HTML will set for the total value in the field, but How can I set for each value separated by comma.
I have a validator which checks whether the user entered at least 2 values
import { AbstractControl } from "@angular/forms";
export function InputValuesValidator(control: AbstractControl): { [key: string]: boolean } | null {
if (control.value) {
let splitString = (control.value).split(',');
if(splitString.length == 1 || splitString[1] == "") {
return { 'valuelisterror': true };
}
}
return null;
}
Can I modify this validator to check for length as well? Please suggest. Thanks.
CodePudding user response:
make your text validation function be like this,
textInputValidation(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const valuesLength = control.value.split(',').length - 1;
if (control.value.split(',')[valuesLength].length>128) {
return {
textLengthError: 'You have entered more than 128 chars '
};
} else {
return null;
}
};
}
You will also have to remove maxlength
property from your HTML, also my suggestion is that use different functions for validation, putting all the validation logic is not a good practice.
CodePudding user response:
It's important when you try to make some component, first try to create a simple model of it, for what you want it's much better if you try to do that:
event.keyCode === 188
mean comma, also you can add Enter or whatever you want; and the input always has a maxlength and user can't type more than it
Html:
<label for="tag" >
<ul>
<li *ngFor="let tag of tags">{{tag}}</li>
<li>
<input id="tag" type="text" maxlength="125" [(ngModel)]="tag" (keyup)="callMe($event)">
</li>
</ul>
</label>
ts:
tags = [];
tag = null;
callMe(event) {
if (this.tag.length <= 128) {
if (event.keyCode === 188) {
this.tags.push(this.tag);
this.tag = null;
}
}
}
Css:
.a {
border: dashed 1px #ccc;
display: block;
}
.a ul li {
display: inline-block;
margin: 0 5px;
list-style: none;
}
input {
border: none;
outline: none;
}
CodePudding user response:
This creates an array of words seperated by a comma and checks them for a length (4 here). Just a rough idea, customize it to your needs.
<input id="license" type="text" formControlName="licenseOwnerName" maxlength="128">
let lic = document.getElementById("license");
lic.addEventListener("input", function(e) {
lic_arr = lic.value.split(",");
for(let word in lic_arr) {
if(lic_arr[word].length > 4) {
alert("too long");
}
}
})