Isuru
Isuru

Reputation: 970

Regex pattern validation Angularjs2

I'm developing an Angular2 application. I'm trying to do a validation when login using a regex pattern.

login.component.ts

import { Component, OnInit } from '@angular/core';
import {AuthenticationService, User} from '../authentication-service.service';
import {TokenService} from '../token.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthenticationService,TokenService]

})

export class LoginComponent {

public user = new User('','','');
public errorMsg = '';

constructor(private _service:AuthenticationService) {
    var ssnRegex='^(\d{6}|\d{8})[-|(\s)]{0,1}\d{4}$';
    this.logout();
}

  login() {
      if(!this._service.login(this.user)){
          this.errorMsg = 'Failed to login';
      }
  }

  logout(){
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      localStorage.removeItem("paydid");
  }
}

login.component.html

<form id="login-form" action="" method="post" role="form" style="display: block;" #roomForm='ngForm'>
        <div class="form-group">
                        <input type="text" required maxlength="12" minlength="12" [pattern]="ssnRegex" ngModel name="capacity" #capacity='ngModel' [(ngModel)]="user.ssn" name="ssn" id="ssn" tabindex="1" class="form-control input-box" placeholder=" Personnummer (ååååmmddnnnn)"
                            value="">
                    </div>
                    <div class="form-group">
                        <div class="row">
                            <div class="col-sm-4 col-sm-offset-4">
                                <span style="color:red; float:left; width: 100px;">{{errorMsg}}</span>
                                <button (click)="login()" class="btn waves-effect waves-light" type="submit" name="action">Login</button>
                            </div>
                        </div>
                    </div>l
                </form>

This is what I have done up to now. But this is not doing the expected validation when login. At the same time, I need to show an error message if the entered string is not following the pattern. I'm new to Angualrjs. Help appreciated. Thanks!

Upvotes: 2

Views: 1365

Answers (1)

Bazinga
Bazinga

Reputation: 11194

You need to change to:

this.ssnRegex='^(\d{6}|\d{8})[-|(\s)]{0,1}\d{4}$';

Example:

@Component({
  selector: 'my-app',
  template: `
    <form #roomForm="ngForm">
       <input type="text" [pattern]="ssnRegex" [(ngModel)]="user.ssn" name="ssn" required #ssn="ngModel">
      {{ssn.valid}}
    </form>
  `,
})
export class App {
  constructor() {
    this.user = {ssn: ""};
    this.ssnRegex = "[A-Za-z]{3}" // Only 3 letters allowed for example
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule],
  declarations: [ App ],
  providers: [SessionService],
  bootstrap: [ App ]
})
export class AppModule {}

Plunker

Upvotes: 1

Related Questions