正则表达式模式验证Angularjs2

时间:2016-10-21 12:13:12

标签: regex validation angular

我正在开发一个Angular2应用程序。我在使用正则表达式模式登录时尝试进行验证。

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>

这就是我现在所做的。但是这在登录时没有进行预期的验证。同时,如果输入的字符串不遵循模式,我需要显示错误消息。我是Angualrjs的新手。帮助赞赏。谢谢!

1 个答案:

答案 0 :(得分:1)

您需要更改为:

allOf

示例:

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

Plunker