Shruti Nair
Shruti Nair

Reputation: 2034

Angular2 form validation with pattern

I'm trying to user the pattern attribute for email in Angular 4.3.0 but the field.errors.pattern returns true even when the email is correct. I'm working on an existing code and this pattern was used in this.I'm also not able to understand the RegEx.

Below is the HTML form

<form #loginform="ngForm" class="form-horizontal  b bg-white padding_default r-2x box-shadow" novalidate role="form">

    <div class="text-danger wrapper text-center" *ngIf="authError">

    </div>
    <div class="animated fadeIn">
        <div class=" m-b-md no-border ">
            <input id="username" type="email" class="form-control input-lg b  text-md" name="username" placeholder="Email" [(ngModel)]="loginData.email"
                autofocus required #username="ngModel" pattern="emailPattern">
            <div *ngIf="username.invalid && (username.dirty || username.touched)" class="alert alert-danger">
                <div *ngIf="username.errors.required">
                    Name is required.
                </div>
                <div *ngIf="username.errors.pattern">
                    Name is invalid
                </div>

            </div>
            <!--<div class="sxo_validate_msg text-danger text-sm" *ngIf="username.touched && isValidEmail">
                            <span>Invalid email address.</span>
                        </div>-->
        </div>

        <div class=" m-b-md no-border">
            <input id="password" type="password" class="form-control input-lg b b-light text-md" name="password" [(ngModel)]="loginData.password"
                placeholder="Password" required #password="ngModel">
            <div class="text-danger sxo_validate_msg text-sm" *ngIf="password.dirty && password.invalid">
                <span *ngIf="password.required">Password is required.</span>
            </div>
        </div>

        <div class="m-b-md m-t-md">
            <label class="i-checks text-sm">
                <input name="rememberme" id="login-remember" type="checkbox" [(ngModel)]="loginData.rememberMe"><i></i> <a href="#">Remember me</a>
            </label>
        </div>

        <div class="controls m-t-md">

            <div class="m-b-lg" *ngIf="showCaptche">
                <re-captcha [site_key]="model.key" (captchaResponse)="setResponse($event)"></re-captcha>

                <!--<div vc-recaptcha
                                theme="'light'"
                                key="model.key"
                                on-create="setWidgetId(widgetId)"
                                on-success="setResponse(response)"
                                on-expire="cbExpiration()"></div>-->
            </div>
            <input class="btn btn-lg btn-dark btn-block" value="Login" (click)="login()" [disabled]="!loginform.form.valid" />
            <div [hidden]="!message" class="alert alert-danger sxo_validate_msg p-t-xs p-b-xs">
                {{message}}
            </div>
        </div>
    </div>


</form>

Below is the pattern

emailPattern:any =  new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

Upvotes: 1

Views: 1855

Answers (3)

Vega
Vega

Reputation: 28738

To understand/learn RegExp : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

The following should work:

 emailPattern:any =  new RegExp(/^(([^<>()\[\]\\.,;:\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,}))$/);

Upvotes: 0

Helen
Helen

Reputation: 103

I have encounter the same problem too and I don't know why regex seems not working in my Angular 4 project. I start using Validators in Angular's FormGroup and the email validation works like a charm in my project.

Here's my snippet of code for my Edit Profile Page (edit-profile.component.html):

<form [formGroup]="editProfileForm" class="form-horizontal" (ngSubmit)="EditProfile()" >
    <div class="form-group">
       <label for="email" class="col-md-4 control-label">E-Mail Address </label>
       <div class="col-md-6">
          <input id="email" type="email" class="form-control" formControlName="email" [(ngModel)]="user.email" required autofocus >
       </div>
    </div>
    <span class="help-block">
       <strong>{{ errors.email }}</strong>
    </span>
    <div class="form-group">
       <div class="col-md-6 col-md-offset-4">
          <button type="submit" class="btn btn-primary" [disabled]="editProfileForm.pristine">
            Update
          </button>
       </div>
    </div>
</form>

and in the edit-profile.component.ts file:

import { NgForm, FormGroup, FormBuilder, FormArray, FormControl, Validators } from '@angular/forms';

  private errors = {
      email: '',
  };

  public editProfileForm: FormGroup;

  constructor(
    private fb: FormBuilder,
  ) {
    this.createForm();
  }

  createForm() {
    // constructor + form Validator
    this.editProfileForm = this.fb.group({
      email: ['', Validators.compose([Validators.required, Validators.email])],
    });
   }

   EditProfile() {
    if (this.editProfileForm.invalid) {
      if (this.editProfileForm.controls['email'].hasError('required')) {
        this.errors.email = 'E-mail name cannot be empty';
      } else if (this.editProfileForm.controls['email'].hasError('email')) {
        this.errors.email = 'E-mail is not valid';
      } 
    } else {
    // submit the form
    }
  }

Hope this helps!

Upvotes: 2

Rahul Singh
Rahul Singh

Reputation: 19640

Angular 4 has a built-in email validation tag that can be added within the input. E.g.:

<input type="email" id="contactemail" email>

This will be valid for a series of numbers and letters then an @ then another series of letters. It will not account for the dot after the @ -- for that you can use the "pattern" tag within the input and your standard regex.

Or if you want to go with pattern try this

<input type="text" name="email" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required email/>

Upvotes: 0

Related Questions