Search code examples
angularangular2-formsangular2-validators

How to validate an email in Angular2?


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.


Solution

  • 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.