在正则表达式中添加多个条件

问题描述

我是使用正则表达式的初学者。我试图在 SuccessFactors Onboarding 1.0 中构建验证。用于手机号码字段。人们应该能够添加最多 15 位数字和以下字符:+ ( ) 和空格。我想禁止人们输入字母(即 ext)。如果格式不匹配,系统应该抛出错误。错误是在页面设置中配置的,正则表达式是一个条件,当不匹配时会导致错误在屏幕上弹出,因此错误消息不需要是表达式的一部分。

我想出了以下代码:^[\d]{1,15}$|\|/[^a-z]+x/$,但该代码仅启用字符数验证并禁用添加字母(在测试时它似乎禁用大写和小写)。我不知道如何添加允许添加上述字符的第三个条件。我尝试使用此代码:[\d]{1,15}$|\[^a-z]+x\|\(?:+()\$,但此代码不允许添加额外字符并禁用错误消息,用户无法继续处理下一页,但错误不会出现在屏幕上,仅字段旁边的红色星号。

我可以请任何人帮我弄清楚如何正确添加最后一段验证,以便允许 + () 和最多 15 位数字等字符,但其他所有内容都会弹出错误。

提前致谢!

解决方法

伪代码

if (string.contains(Regex("[^\d\+\(\) ]")) throw Exception() else accept
if (string.length > 15 || string.isEmpty()) throw Exception() else accept

如果您需要更严格的条件,请举例说明什么是正确的输入,什么是不正确的

,

不用担心,除了少数几个,我们都是使用 RegEx 的初学者! ?

一般来说,限制电话号码的有效或无效符号可能根本不是一个好主意。有时,您会看到末尾的分机号码在视觉上被一个减号分隔(如“0123 45 678 - 9”)。有些人可能会在括号中添加国家代码或拨号代码,其他人则不会。

还要考虑使用非西方字符输入(或从来源粘贴)的数字,作为中文括号 ( )(它们看起来很相似,但实际上是它们自己的字符,周围有更多的空格!) - 应该那些不也被认为是有效的吗?

如果有人想输入无效号码,他们无论如何都会输入(“555-00000000”...)!

但如果您真的想将输入的字符串限制为数字和字符 ()+- ,这就是您需要的正则表达式:

const rx = /^[0-9()+\- ]+$/;

// should be false:
console.log(rx.test("abc 123"));

// should be true:
console.log(rx.test("+49 123 456 789 - 0"));
console.log(rx.test("+49 (0) 123 456 789 - 0"));
console.log(rx.test("555-000 0000"));

// this will fail,because of the use of Chinese parenthesis,// which is the only difference to the second number in the  previous block
console.log(rx.test("+49 (0)123 456 789 - 0"));

// of course,these would also be considered valid,// unless you'd implement some more sophisticated checks
// - but is it really worth the trouble?
console.log(rx.test("((( 12345"));
console.log(rx.test("++++"));

让我为你分解一下表达:

/^[0-9()+\- ]+$/
 ^- beginning of the string
  ^- start of the character group
   ^- all the characters we want to allow
      (we have to escape the -,because otherwise
      it would denote an invalid character range)
            ^- end of the character group
             ^- + means: at least one,or more of those characters
              ^- end of the tring

构建、检查和验证正则表达式的好地方,尤其是在开始时,是正则表达式测试工具,例如(无特定顺序):regex101.comregextester.com 或 {{3} }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...