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.

Matthew Green
  • 10,161
  • 4
  • 36
  • 54
JMon
  • 3,387
  • 16
  • 63
  • 102
  • Possible duplicate of [Generic mail validator in Angular2](http://stackoverflow.com/questions/34072092/generic-mail-validator-in-angular2) – phuzi Apr 06 '17 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. ```
    ```
    – kpollock Apr 06 '17 at 13:42

2 Answers2

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>
Pramod Patil
  • 2,704
  • 2
  • 14
  • 20
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;
                }
        }
Thulasi
  • 193
  • 1
  • 10