-1

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.

Saswat
  • 12,320
  • 16
  • 77
  • 156

2 Answers2

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

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • 1
    Great! This one is the actual answer I needed more. It shows how I can use multiple validation rules! I was about to post a question on how to have multiple validation rules on a single . Validators.compose does the trick. Many many thanks. Moreover, Validators.email also checks whether an email is valid or not. Hence, we don't need the preg match pattern. – Saswat Apr 06 '18 at 09:23
  • Glad I could help :) – Tomasz Kula Apr 06 '18 at 09:29
  • 1
    :). I am posting another question. Hope you can help me in that too. :) – Saswat Apr 06 '18 at 09:30
  • Here's another question. https://stackoverflow.com/questions/49689689/how-to-show-different-validation-messages-for-email-validation-in-angular2-using – Saswat Apr 06 '18 at 09:34
1

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]
});
Gianluca Paris
  • 1,391
  • 1
  • 14
  • 25