输入模式属性似乎不接受以(/ regexp /)变形的正则表达式

时间:2018-10-10 13:54:16

标签: regex angular html5 typescript

我有此有效的输入验证

<input class="form-control" pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,12}$" placeholder="" type="password" required>

我正在尝试将模式存储在passwordPattern变量中,并将其注入html

    import { Component, OnInit} from '@angular/core';
    @Component({
      selector: 'my-component',
      templateUrl: './my-component.html',
      styleUrls: ['./my-component.scss']
    })
    export class myComponent implements OnInit {
    passwordPattern:RegExp;
     constructor() {
// 1 digit, 1 letter, minimum 8 chars and maximum 12 chars
      this.passwordPattern = /^(?=.*\d)(?=.*[a-zA-Z]).{8,12}$/ ;
      }

    ngOnInit() {}

    }

html

   <input class="form-control" [pattern]="passwordPattern" placeholder="" type="password" required>

输入模式属性似乎不接受以/ /(/ regexp /)变形的正则表达式。 我试图删除它并将其包装为字符串,但是它不起作用(this.passwordPattern = '^(?=.*\d)(?=.*[a-zA-Z]).{8,12}$';),我也试图使用new RegExp()this.passwordPattern = new RegExp("(?=.*\d)(?=.*[a-zA-Z]).{8,12}"))添加模式不起作用,好吧,寻找实现此目的的正确方法,我的目标是让这种模式作为全局变量抛出应用程序。任何帮助,将不胜感激。

在此处查看示例https://jsfiddle.net/1hk7knwq/10565/

1 个答案:

答案 0 :(得分:0)

请将您的类变量值修改为:

this.passwordPattern = new RegExp("(?=.*\d)(?=.*[a-zA-Z]).{8,12}") ;

现在,您将使用RegExp构造函数创建正则表达式对象,以将文本与模式匹配。这将起作用。