0

I want to validate the username with below condition

  1. Accept only Characters and NUmbers

  2. Accept " _ " or " . "(either any one)

Here is my code

<input type="text" class="form-control" [maxlength]="50" name="userName" placeholder="User Name"
#userName="ngModel" ngModel [(ngModel)]="UserName" (keypress)="userNameValidation($event)">



userNameValidation(event: any) {
  const pattern = /^[a-zA-Z0-9\_\.]+$/
  const inputChar = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  if (!pattern.test(inputChar)) {
    event.preventDefault();
  }
}

Can anybody help me to write the either or condition???

Angel Reji
  • 533
  • 2
  • 11
  • 26

1 Answers1

0

How about using the JS string function string.includes? See the docs here

userNameValidation(event: any) {
  const pattern = /^[a-zA-Z0-9\_\.]+$/
  const inputChar = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  
  let includesBothDotAndUScore = inputChar.includes("_") && inputChar.includes(".");

  if (!pattern.test(inputChar) || includesBothDotAndUScore) {
    event.preventDefault();
  }
}

Also, I believe you can use UserName in the place of inputChar.

Edwin Chua
  • 658
  • 1
  • 8
  • 20