angular regex不适用于12位验证检查



config.newValue的值为"888888888888",config.regex的值为"/[0-9]{12}/"

let matches = String(config.newValue).trim().match(config.regex);

变量匹配应将值返回为true,但返回的值为null。

有人能帮助它不接受正确的验证吗。验证只是检查数字的大小是否为12,以及数字是否为0到9。

您有三个问题。

  1. 如果要检查值长度是否正好为12,则正则表达式应为/^[0-9]{12}$/

  2. 我猜你用const config.regex = "/^[0-9]{12}$/"这样的引号来定义config.regex。您必须定义不带引号的正则表达式变量,如const config.regex = /^[0-9]{12}$/

  3. 方法match返回匹配的字符串。如果您只想要truefalse,可以使用test方法。CCD_ 11。

这是我的建议

const config = {
newValue: "888888888888",
regex: "^[0-9]{12}$",
}
const allMatches = String(config.newValue).trim().match(config.regex);
const hasMatch = allMatches && allMatches.length > 0;
const fistMatch = hasMatch ? allMatches[0] : undefined; 

我创建了一个工作示例。单击链接,然后单击右侧的[运行],您将看到控制台日志输出结果

工作字体操场

最新更新