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

3
  • 1
    Possible duplicate of Angular2 email validation Commented Apr 6, 2018 at 8:32
  • 1
    regex Commented Apr 6, 2018 at 8:57
  • 2
    EmailValidator Commented Apr 6, 2018 at 9:05

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 <input>. 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.
Glad I could help :)
:). I am posting another question. Hope you can help me in that too. :)
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] }); 

2 Comments

Email like [email protected] isn't detected as valid mail using your script.
Build your own regex, that is an example for validating a pattern

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.