简体   繁体   English

正则表达式允许数字和数字验证模式

[英]Regular expression allow numbers and digits validation pattern

I am trying to check if a form input is valid based on a regex pattern using javascript.我正在尝试使用 javascript 根据正则表达式模式检查表单输入是否有效。

The form input should look like this: xxxx-xxx-xxxx allowing for both numbers and letters表单输入应如下所示: xxxx-xxx-xxxx 允许数字和字母

Right now it only works with digits as I have it setup which is now being changed to allow letters as well.现在它只适用于数字,因为我已经设置了它,现在它也被更改为允许字母。 is there a way to change the regex I have to allow numbers and letters and still format as is?有没有办法改变正则表达式我必须允许数字和字母并且仍然按原样格式化?

4 letters or numbers A DASH 3 letters or numbers A DASH 4 letters or numbers 4 个字母或数字 A DASH 3 个字母或数字 A DASH 4 个字母或数字

validation rule
  medNumber: [
          {
            required: true,
            pattern: /^\d{4}?[- ]?\d{3}[- ]?\d{4}$/,
            message: "Please enter your #.",
            trigger: ["submit", "change", "blur"]
          }
        ],

[A-Za-z0-9] will match only alphanumeric characters. [A-Za-z0-9]将仅匹配字母数字字符。

/^[A-Za-z0-9]{4}?[-]?[A-Za-z0-9]{3}[-]?[A-Za-z0-9]{4}$/

I've also removed the spaces from within your instances of [- ] because that will allow matches such as我还删除了[- ]实例中的空格,因为这将允许匹配,例如

xxxx xxx xxxx

In your spec you mention a dash is required, not a space.在您的规范中,您提到需要破折号,而不是空格。

The rule \d allows only for digits.规则\d只允许数字。 So you need to change every occurrence of this to \w , which allows any alphanumeric character (letters and digits).因此,您需要将每次出现的 this 更改为\w ,它允许任何字母数字字符(字母和数字)。 So you'd get the following:所以你会得到以下信息:

/^\w{4}?[- ]?\w{3}[- ]?\w{4}$/

For future reference, I'd suggest looking at regexone.com .为了将来参考,我建议查看regexone.com It has helped me a ton with learning all the regex rules.它帮助我学习了所有的正则表达式规则。 You can also use regex101.com for easy testing of regex patterns.您还可以使用regex101.com轻松测试正则表达式模式。

Edit:编辑:
I was probably a bit too quick on this one.我可能在这方面有点太快了。 As @David mentioned in the comment, \w also includes underscores.正如评论中提到的@David, \w还包括下划线。 If you don't want that, you should look at his answer instead:)如果你不想那样,你应该看看他的答案:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM