Reputation: 12836
I am using FormGroup, FormBuilder and Validators class to validate a form in Angular2 app.
This is how I am defining the required validation rules for email and password validation:-
export class LoginComponent implements OnInit {
loginFormGroup:FormGroup;
adminLoginmodel = new Admin('', '', '', 'Emailsss','Passwordsss');
constructor(
private route: ActivatedRoute,
private router: Router,
private _adminLogin: AdminLoginService,
fb: FormBuilder
){
this.loginFormGroup = fb.group({
'email' : [null, Validators.required],
'password': [null, Validators.required]
});
}
}
How can I validate if a given string is a valid email?
Note:
Someone has just tried to mark this question as a duplicate of this question.
My question specifically asks about implementation of FormGroup and FormBuilder, which was even stated at the beginning of the question. This is a fine example to show how some good and valid questions get judged unfairly. Hope the moderators and other so-called "stackoverflow-community-builders" won't edit this question to remove this section.
Upvotes: -1
Views: 377
Reputation: 16837
this.loginFormGroup = fb.group({
'email' : [null, Validators.compose([Validators.required, Validators.email])],
'password': [null, Validators.required]
});
Compose multiple validators into a single function that returns the union of the individual error maps.
Upvotes: 2
Reputation: 1429
You have to use pattern validator with a regex:
this.loginFormGroup = fb.group({
'email' : [null, 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,}))$')],
'password': [null, Validators.required]
});
Upvotes: 1