我有一个正则表达式模式,它验证三位数字
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("123.") // false
Run Code Online (Sandbox Code Playgroud)
我想使用此正则表达式作为文本框的输入限制.
基本上,如果新值匹配,我允许输入字符,否则我会阻止它.
问题是没有值会匹配,因为"1"不是完全匹配,并且不允许我输入它.
是否有任何方法可以在javascript中测试regEx的部分匹配?
/^\d{3}$/.test("123") // true
/^\d{3}$/.test("12") // "partial match"
/^\d{3}$/.test("a12") // false
Run Code Online (Sandbox Code Playgroud)
编辑
\ d {3}只是一个例子.我需要使用电子邮件正则表达式或手机正则表达式作为输入限制.
"email" // true
"email@" // true
"email@@" // false
"@yahoo.com" // false
Run Code Online (Sandbox Code Playgroud)
编辑2
我有一个textBox插件,其输入限制基于正则表达式.
正则表达式可以是任何东西,十六进制颜色正则表达式,例如:(#){1}([a-fA-F0-9]){6}
我需要阻止用户插入与正则表达式不匹配的字符.
例如,如果文本框为空,则第一个允许的字符为"#".
但是如果我对正则表达式测试"#"字符,它将返回"false",因为"#"本身无效.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // false
Run Code Online (Sandbox Code Playgroud)
但与此同时,"#"部分有效,因为它尊重正则表达式格式(我应该允许用户输入)
我需要知道的是,如果我可以验证字符串是否是正则表达式的部分匹配,那么我可以允许用户键入字符.
/^(#){1}([a-fA-F0-9]){6}$/.test("#") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#0") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#00") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#0000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#00000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000") // is a partial match, allow type
/^(#){1}([a-fA-F0-9]){6}$/.test("#000000D") // is not a match, prevent typing
Run Code Online (Sandbox Code Playgroud)
您可以在表达式中指定一个范围,以便它匹配一到三位数之间的任何数字,如下所示:
/^\d{1,3}$/.test("1") // true
/^\d{1,3}$/.test("12") // true
/^\d{1,3}$/.test("123a") // false
Run Code Online (Sandbox Code Playgroud)