Angular 4 reactive form Email validation by regular expression fail

angular 6 email validation example
angular reactive form validation regular expression
custom email validation in angular 6
reactive form pattern validation
angular 7 form validation example
form validation in angular 2
angular 9 form validation
angular 4 regex match

I'm using a reactive form to get user input. Not satisfied with the EmailValidator I'm using a pattern.

emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$';
this.email = new FormControl('', [Validators.required, Validators.pattern(emailRegEx)]);

And the HTML:

<input type="email" formControlName="email" [ngClass]="contactForm.get('email').errors && (contactForm.get('email').dirty || isButtonClicked) ? 'contact-input input-error' : 'contact-input'">

But here's the thing, for some reason the regex is accepting 4 chars after the @, without a period. name@d --> error name@doma --> no error name@domain. --> error name@domain.com --> no error

I checked this regex in multiple online regex testers, and they all only accept the last example above, none of them accept the second one.

EDIT: The regular expression is fine and works well, the problem is that somehow the pattern validator isn't parsing the regex correctly, or something.

The pattern is not correct as a string. In deed you are inside a string so to escape '.' you need to use double backslash like:

emailRegEx = '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$'

Or if you want to avoid doing so i suggest to use:

emailRegEx = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/

Edit: Keep in mind that this is a simple pattern that exclude a lot of valid email address (see RFC 5322 (sections 3.2.3 and 3.4.1) and RFC 5321). For example the angular build in email validator use the following pattern

/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/

Email Validation in Angular: Full Guide, To assist us in displaying useful validation and error messages to users, we'll include the In Angular reactive forms, the component class is the main source of truth. Here is the regex Angular email validation pattern: [a-z]{2,4}$" class=​"form-control" name="primaryEmail" [(ngModel)]="userModel. We will use a regular expression to validate the password. We will validate the following four conditions using the regular expression: The password should be a minimum of eight characters long. It has at least one lower case letter. It has at least one upper case letter. Contains at least one number.

You can use CustomValidator package that offers too much types of validation :https://www.npmjs.com/package/ng2-validation

import it like that :

import { CustomValidators } from 'ng2-validation';

and use it in your form control :

this.email = new FormControl('', [Validators.required, CustomValidators.email]);

Regards,

Angular Email Validation Example, Email can be validated using Angular PatternValidator directive with a regex. If pattern does not match, we will get validation error. In this way  Pattern validation: This allows you to specify a regular expression (regex) Angular email validation pattern that should match the user-provided value before validation can occur. Custom validation : You can also create your own custom email validators, especially if the built-in validators do not match your specific use case.

import {Component} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
    templateUrl: './forgot-password.component.html',
    styleUrls: ['./forgot-password.component.scss']
})
export class ForgotPasswordComponent {

    psResetForm: FormGroup;

    constructor(private fb: FormBuilder) {
        this.psResetForm = fb.group({
            'email': [null, Validators.compose([Validators.required, Validators.email])]
        });
    }

    makeRequestToResetLink(formData, valid: boolean) {
        if (valid) {
            alert(formData.email);
        }
    }

}

Your Template should look like this

<form [formGroup]="psResetForm" (ngSubmit)="makeRequestToResetLink(psResetForm.value,psResetForm.valid)">
    <input type="email" formControlName="email"/>
    <button type="submit">
        submit
    </button>
</form>

How to Validate Angular Reactive Forms, ng new angular-forms-validation --routing=false --style=scss We will validate the following four conditions using the regular expression: If the password fails the regex check, we will set the invalidPassword property to true. <input type="​text" class="form-control" formControlName="email"> <span  If we are using Angular 2, we need to write novalidate attribute in our form element to use Angular form validation. In Angular 4 template-driven form we can use ngNoForm to enable HTML 5 validation. Here in our example we will provide demo for Template-driven form as well as Reactive form for Angular email validation.

Angular 4 reactive form Email validation by regular expression fail, Angular 4 reactive form Email validation by regular expression fail. I'm using a reactive form to get user input. Not satisfied with the  While Angular does provide various input field validators (i.e. email), there are use cases where you will need to create your own validators. That’s when the power of regular expressions shines…

EmailValidator, The following example shows how to add an email validator to an input attached to an ngModel binding. Master/Detail Components. A directive that adds the email validator to controls marked with the email attribute. The directive is provided with the NG_VALIDATORS multi-provider list. The following example shows how to add an email validator to an input attached to an ngModel binding. Method that validates whether an email address is valid.

How to validate default and custom reactive forms in Angular, When using reactive forms, Angular offers only a hand full of very generic use https://regexr.com/ to test your regular expression. it's great! We used the required and email validators from Angular. If there are any, we find the correct error message that came from the validationMessages method and pass back the form  Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors, which results in an INVALID status, or null, which results in a VALID status. You can then inspect the control's state by exporting ngModel to a local template variable.

Comments
  • Possible duplicate of How to validate an email address using a regular expression?
  • This is not a duplicate, I made a stackblitz reproducing : stackblitz.com/edit/stackoverflow-49175054 The regex looks good, tried in the notepad++ search and behave well.
  • I'm still not entirely convinced that the problem of validating emails with regex hasn't been redone a hundred times on SO, but I retracted by close vote anyway. :)
  • Why is this better than angular's build-in EmailValidator, the HTML5 input type="email" validator, or the above regex?
  • why downvote ? i did not said that is better , i suggested a solution for his problem my friend :)
  • It's a simple library suggestion, which should be a comment. The code is boilerplate and doesn't add any value as an answer (OP knows how to load and instantiate a validator) so the answer boils down to the link. What would add value would be to explain, in-line, why this library fixes OP's problem