1

I made an angular 6 custom validators to check if a user entered the 3 required digits or not. Here is my input:

<mat-form-field appearance="outline" color="warn">
     <mat-label>Last 3 digits</mat-label>
     <input matInput type="text" formControlName="last_three_digits" placeholder="Last 3 digits">
</mat-form-field>&nbsp;

And here is how I declare it in reactive form:

  'last_three_digits': new FormControl('', [Validators.required, validatePositiveNotNull, validateLengthThree])

I tried to add Validators.pattern("[0-9 ]*") but it keep letting the user to add - or + or = or /.

I just need to strict into number of length = 3.

Here is the script:

export function validateLengthThree(control: AbstractControl)
{
  if(control.value==null || control.value==undefined)
  {
    return { validPositive: true}
  }
  else if(control.value.length<3 && control.value!=null && control.value!=undefined)
  {
    return { validPositive: true}
  }
  else if(control.value.length>3)
  {
    return { validPositive: true}
  }
  return null;
}

I tried to change the type of input to number but still the same.

I used this pattern /^\d+$/ from this answer on stack, and the input still accepting the special characters and validating the form.

P.S. I added the null and undefined conditions in my custom validators, because when I focus out from this input, and while it's empty, it throw an error saying that it can't run on null values.

alim1990
  • 4,656
  • 12
  • 67
  • 130

1 Answers1

1

use a directive on your input, to prevent the key pressed

107 = "+"

109 = "-"

111 = "/"

187 = "="

<input keysban="[107,109,111,187]" type="text">

the directive

import { Directive, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[editable]'
})
export class EditableDirective {
  @Input() keysban: number[];

  @HostListener('keydown', ['$event']) onKeyDown(event: KeyboardEvent) {
    // check banned key
    if (this.keysban) {
      if (this.keysban.indexOf(event.keyCode) > -1) {
        event.preventDefault();
      }
    }
    console.log(event.keyCode);
  }

  constructor() { }

}

don't forget to add your max length validator