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>