0

I am trying to do some email validation on an angular 2 form, however I cannot make it work.

Here is my register.html form :-

<div class="row">
<div class="col-lg-10 col-offset-2">
<div class="well bs-component">
  <form name="registerForm" class="form-horizontal" (ngSubmit)="onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber)" >
    <fieldset>
      <legend>Register</legend>
      <div class="form-group">
        <label for="username" class="col-lg-2 control-label">UserName</label>
        <div class="col-lg-10">
          <input type="text" class="form-control" name="username" [(ngModel)]="username" placeholder="Username"  required minlength="4" maxlength="20">
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-lg-2 control-label">Email</label>
        <div class="col-lg-10">
          <input type="text" class="form-control" name="email" [(ngModel)]="email" placeholder="Email"  required minlength="4" >
          <div *ngIf="email.dirty && !email.valid" class="alert alert-danger">
                        <p *ngIf="email.errors.required">mailAddressis required.</p>
                        <p *ngIf="email.errors.incorrectMailFormat">Email format is invalid.</p>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label for="password" class="col-lg-2 control-label">Password</label>
        <div class="col-lg-10">
          <input type="password" class="form-control" name="password" [(ngModel)]="password" placeholder="Password"  required minlength="4">
        </div>
      </div>
      <div class="form-group">
        <div class="col-lg-10 col-lg-offset-2">
          <button type="reset" class="btn btn-default">Cancel</button>
          <button type="submit" class="btn btn-primary">Register</button>
        </div>
      </div>
    </fieldset>
  </form>
</div>

and in my register.component.ts I have the following:-

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {UserService} from 'app/services/user.service';
import {FormGroup, FormControl, Validators} from "@angular/forms";

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  registerForm: FormGroup;

  constructor(private _userService:UserService, private _router:Router) { }

  ngOnInit() {
    this.registerForm = new FormGroup({
      email: new FormControl('', this.validateEmail)
    });
  }

    onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber){
    this._userService.register(email, password, name, surname, username, homephonenumber, mobilenumber)
      .subscribe((result) => {
      // if(result.access_token != null) {
      //   this._router.navigate(['']);
      // }
    });
  }

  validateEmail(c: FormControl) {
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    return EMAIL_REGEXP.test(c.value) ? null : {
      validateEmail: {
        valid: false
      }
    };
}

Do I need anything else to make the validation work?

Thanks for all your help and time.

2
  • Possible duplicate of Generic mail validator in Angular2 Commented Apr 6, 2017 at 13:33
  • have you tried checking form.controls.email.errors to see if the validator is working? I don't see any code to show anything when the validation fails... e.g. ``` <div *ngIf="form.controls.email.errors.validateEmail" Email Invalid. </div>``` Commented Apr 6, 2017 at 13:42

2 Answers 2

2

HTML5 is having email type that validates by default.

<input type="email" class="form-control" name="email" [(ngModel)]="email" placeholder="Email"  required minlength="4" >

Other way around is to use ng-pattern

<input ng-pattern = '/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i' type="email" name="email" class="form-control" ng-model="email" required="" />
          <p class="help-block error-block">Enter a valid email address.</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks..Please upvote so that others can also get benefit
0
try like this:   

 Html:

     <form id="frmForgetPwd" name="frmForgetPwd" #frm="ngForm">
                            <div class="form-group">
                                <label>Registered Email Address</label>
                                <input type="email" class="form-control" focus
                                       id="emailID" name="emailID" autofocus
                                       #email="ngModel"
                                       ngModel
                                       required>
                            </div>
                            <button type="submit (click)="forgotPassword(email.value)">
                                Submit
                            </button>
                        </form>

    component:

            forgotPassword(emailid: string) {
                this.errors = [];
                if (emailid == "") {
                    this.errors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
                    return false;
                }
                let EMAIL_REGEXP = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                if (!EMAIL_REGEXP.test(emailid)) {
                    this.errors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
                    return false;
                }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.