Home > Net >  How to take input of maximum input length 6 as number and it should be separated with " , "
How to take input of maximum input length 6 as number and it should be separated with " , "

Time:10-27

How to take input of maximum input length 6 as number and it should be separated with " , "(comma) example : 123456, 234567, 345678. Do we need to add function for it ? Using angular framework, typescript

<form-field [input]="['Codes', formGroup="some-naming", number]">

CodePudding user response:

You will need to both validate the input as fitting your requirements and then also perhaps format it on screen.

Validating a number input using a phone number as an example:

HTML input type for phone number

Formatting the input:

How to format input in html using javascript

CodePudding user response:

You can make a custom validator and return custom error messages as per the docs:

https://angular.io/guide/form-validation#adding-custom-validators-to-reactive-forms

Stackblitz Example: https://stackblitz.com/edit/angular-ivy-po5ulp?file=src/app/app.component.ts

/** Comma separated integers, max 6 digits */
function customValidator(
  control: AbstractControl<string>
): ValidationErrors | null {
  if (!control.value) return null;
  const numbers = control.value.split(',');
  for (const num of numbers) {
    const n = num.trim();
    if (n === '') continue;
    if (!n.match(/^[0-9] $/)) return { notInt: n   ' is not an integer' };
    if (n.length > 6) return { tooLong: n   ' is too many digits' };
  }
  return null;
}

Add it to a form control via the constructor

control = new FormControl('', customValidator);

You can get a single error like so:

  getError() {
    const err = this.control.errors;
    if (!err) return null;
    for (const key in err) return err[key];
  }

and the html can be:

<input [formControl]="control" />
<p *ngIf="control.errors" [ngStyle]="{color:'red'}">{{getError()}}</p>
  • Related