我正在尝试使用正则表达式验证字段名称以匹配 JavaScript 中的特定格式。
我需要输入类似于这样的字符串:
单词\单词\单词
所以输入的任何东西都不能为空,而且必须是反斜杠分隔的三个单词。
这是我正在使用的代码,但我不确定该模式的语法是否正确?!!
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
}
else
{
alert("match");
}
}
任何帮助将不胜感激!!!
最佳答案
试试 /^[a-z]+\\[a-z]+\\[a-z]+$/
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
} else {
alert("match");
}
}
如果要让单词匹配不区分大小写;
`/^[a-z]+\\[a-z]+\\[a-z]+$/i`
如果您想将“单词”的定义范围更广一些,并允许它由字母数字字符和下划线组成;
`/^\w+\\\w+\\\w+$/i`
关于JavaScript 正则表达式验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32004990/