-2

How to achieve this I am using Angular 7 and typescript I have a Input field data like this DK9520000123456789 So i want the user to restrict to enter the first two characters only be letters and not numbers. ("DK"9520000123456789) I do not want the user to enter numbers in the first two characters.

<form class="bank-form-container {{ labelClass }}" [formGroup]="bankForm">
  <div class="col-md-6 pl-0">
    <label for="bankAcc" class="bank-label"> {{ label }}<i class="validateField">*</i> </label>
    <input
      [type]="isMaskedBankAcc ? 'password' : 'text'"
      (keypress)="numericOnly($event)"
      oninput="this.value = this.value.toUpperCase()"
      id="bankAcc"
      sp-popover
      name="bankAccountNumber"
      placement="right"
      placeholder="{{ placeHolder }}"
      class="form-control sp-focus text-uppercase"
      formControlName="bankAcc"
      appBlockCopyPaste
      autocomplete="off"
      (blur)="maskAndEncryptBankNumber()"
      (focus)="unmaskBankNumber()"
      [ngbTooltip]="toolTip"
      [pattern]="pattern"
      [required]="isRequired"
    />

ngOnInit() {



    this.bankForm = new FormGroup({
      bankAcc: new FormControl({ value: this.value ? this.value : '', disabled: this.isDisabled }, [
        Validators.required,
        Validators.pattern(/^\w{2}\d+$/i),
      ]),
      bankConfirmedAcc: new FormControl({ value: this.value ? this.value : '', disabled: true }, [
        Validators.required,
        Validators.pattern(/^\w{2}\d+$/i),
        this.checkMatchingValues.bind(this),
      ]),
    });

    this.checkFormValues();
    this.unmaskConfirmedBankNumber();
  }
Sai Ram
  • 41
  • 7

1 Answers1

0

I assume you're using a FormControl for that.

Then simply add pattern validator: Validators.pattern(/^\w{2}\d+$/i). It requires a user to enter 2 letters and then only numbers.

this.form = new FormGroup({
    inputField: new FormControl('', {
        validators: [Validators.required, Validators.pattern(/^\w{2}\d+$/)],
    }),
});

in template

<input [formControl]="form.get('inputField')">
<div *ngIf="form.get('inputField').hasError('pattern')">wrong pattern</div>
satanTime
  • 12,631
  • 1
  • 25
  • 73