Regex angular ngModel

Asked

Viewed 171 times

0

Hello, I have a problem with regex and angular.

I have an input that uses ngModel, and I need to use a regex on it to prevent the user from initially entering a number, that is, the first input must not be a number.

The problem is, I can’t find a regex that does that and I can’t apply any regex with ngModel.

Could someone please help me. My input is like this at the moment:

 <input 
     placeholder="Input name" 
     class="inputs" 
     value="{{input.inputField}}"
     pattern="^[a-z]"
     [(ngModel)]="input[i].inputField" />

Thank you in advance...

  • 1

    You can create a function and call it in the onKeyDown attribute of your input, and in it do this first character validation as letter and the rest as numbers.

  • It’s not just changing the pattern for ng-pattern? https://docs.angularjs.org/api/ng/directive/ngPattern#Usage

  • uses directive, easier

  • http://kazale.com/angular-2-mascara-entrada-dados-input-mask-diretivas/

1 answer

2


You don’t need regular expression to do this validation, you can take the first value of input with the method replace() and check if it is a number with the method isNaN():

TS

if(e.target.value.substr(0,1) == isNaN(e.key)) {
  this.valores = undefined;
  this.message = true;
  return;
} 

HTML

<input placeholder="Input name" [(ngModel)]="valores" (keydown)="eventos($event)" 
 [readOnly]="message" (click)="volta()"/>

You can see an example working here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.