Reputation: 706
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
[email protected]
--> 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.
Upvotes: 8
Views: 22425
Reputation: 7133
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])?)*$/
Upvotes: 17
Reputation: 10029
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>
Upvotes: -2
Reputation: 3297
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,
Upvotes: 1