我能想到的是使用示例,即应该匹配正则表达式的典型输入:
var examples = {
"Date": [
"2010-01-01", "10-01-01", "2010-1-1", "10-1-1", "01-01-2010", "01-01-10", "1-1-2010", "1-1-10",
"2010/01/01", "10/01/01", "2010/1/1", "10/1/1", "01/01/2010", "01/01/10", "1/1/2010", "1/1/10"
],
"Int": [
"0", "0123456789"
],
"VarChar": [
"a", "abcdefghijklmnopqrstuvwxyz", "A", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
]
};
然后,如果输入的正则表达式匹配特定类型的示例之一,您可以验证它:
$("#pattern").blur(function() {
var pattern = this.value;
var regex = new RegExp(pattern);
var type = $("select").val();
var validPattern = false;
if (type in examples) {
for (var i = 0; i < examples[type].length, i++) {
var example = examples[i];
if (regex.test(example)) {
validPattern = true;
break;
}
}
} else {
alert("No examples found for type '" + type + "'");
}
if (validPattern) {
alert("Valid pattern");
} else {
alert("Invalid pattern");
}
});
主要问题是它不会涵盖复杂/特殊的正则表达式。例如,对于给定的示例,Int
with/^5/
将无效,因为没有以 .Int
开头的示例5
。VarChar
with/bca/
也无效。但是,如果您设法为每种类型提供足够的示例,这可能会满足您的需求:)
你可以在这里看到一个例子。