Reputation: 309
I am tryng to do form validations and run into some issue, if I use angular email validator like this:
<input type="email" class="mail" email name="emailField" [(ngModel)]="email" #emailField="ngModel">
and put it into form by formGroup:
<form [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >
<input type="email" class="mail" email name="emailField" [(ngModel)]="email" #emailField="ngModel">
<div class="emailinvalid" *ngIf="emailField.invalid && emailField.touched">
<span *ngIf="emailField.hasError('email')">
Please enter the correct email, this email not valid.
</span>
</div>
<br>
</form>
in that way email-validation doesn't work, so I am looking for the way to fix it, here is my ts code:
export class ContactComponent {
myForm: FormGroup;
email: string;
username: string;
surname: string;
message: string;
constructor(fb: FormBuilder) {
this.myForm = fb.group({
'username': ['', Validators.required],
'surname': ['', Validators.required],
'message': ['', Validators.required],
});
}
}
username
, surname
and other inputs I use in my form(formGroup) above, I've just cut it off to clean the code a little in example.
Upvotes: 19
Views: 24077
Reputation: 11
Validators.pattern (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
The above pattern works fine for me as Validators.email
validates till we enter a @ .post
that it is making the field as valid.
Upvotes: 1
Reputation: 73387
You seem to have an odd mix of template and reactive form. I suggest you use a reactive form and the inbuilt validator email
and at the same time, remove any ngModel
.
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
username: ['', Validators.required],
surname: ['', Validators.required],
message: ['', Validators.required],
email: ['', Validators.email]
});
}
and the template would then look something like this:
<form [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >
<input formControlName="username" >
<!-- more fields here -->
<input formControlName="email" >
<span *ngIf="myForm.hasError('email', 'email') && myForm.get('email').touched">
Please enter the correct email, this email not valid.
</span>
</form>
DEMO (just for clearly show the validator, I've removed the touched
)
Upvotes: 33
Reputation: 9402
You can have a validator.ts file
const pureEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
export const regexValidators = {
phone: '[\+][0-9() ]{7,}$',
email: pureEmail,
};
And use in your components like:
this.myForm = fb.group({
'username': ['', Validators.required],
'surname': ['', Validators.required],
'message': ['', Validators.required],
'email': ['', [Validators.required,Validators.pattern(this.validators.email)]]
});
Upvotes: 6