1

Link to a working example - https://angular-gej8ow.stackblitz.io. Link to code - https://stackblitz.com/edit/angular-gej8ow

Description -

When I enter 'johndoe@dsx.com' in the input it is flagged as a valid email by both, the RegeExp in TypeScript and the pattern attribute. But, the email 'johndoe@dsx.coms' is flagged as valid by RegExp and invalid by the pattern attribute. Is there a difference between how the regex is tested by these two?

Here is the TypeScript code, it is being used in .ts file -

emailRegex = new RegExp("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$")

checkEmail(email: string) {
  if(this.emailRegex.test(email)) {
    console.log("Email is valid")
  } else {
    console.log("Email is not valid");
  }
}

HTML code. in the .html file -

<mat-form-field>
  <input
    required
    matInput
    placeholder="Email"
    ngModel
    name="email"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
    #email="ngModel"
    (keyup)="checkEmail(email.value)"
    (blur)="checkEmail(email.value)"
    (change)="checkEmail(email.value)"
  >
  <mat-hint>Email is required.</mat-hint>
  <mat-error>
    Email is not valid.
  </mat-error>
</mat-form-field>

enter image description here

limitlessriver
  • 751
  • 1
  • 6
  • 9
  • The regex must be declared as `emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/` – Wiktor Stribiżew Dec 14 '18 at 21:13
  • If you want .coms to be valid, change the `{2,3}` at the end to `{2,4}` – emsimpson92 Dec 14 '18 at 21:14
  • You can use `` to use the built in email validator. – Reactgular Dec 14 '18 at 21:19
  • @WiktorStribiżew Thanks! It works. Now, they are consistent. Is there a reason for using ^? It seems to work without the ^. – limitlessriver Dec 14 '18 at 21:35
  • This is more a JS related problem, so I closed as a duplicate: 1) to define a ``\`` inside a string literal, you need to double it, thus, it is safer to use *regex* literal notation, 2) to match entire string, you must add `^` at the start and `$` at the end of the pattern, else, JS regex may find partial matches (like `$$%#$^$johndoe@dsx.com$@#%^#`) – Wiktor Stribiżew Dec 14 '18 at 22:10

0 Answers0