如何使用正则表达式检查用户输入是否仅包含特殊字符? [英] How to use regex to check that user input does not consist of special characters only?

查看:275
本文介绍了如何使用正则表达式检查用户输入是否仅包含特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对不允许使用特殊字符的字段进行验证,这意味着 AB#,A89 @,@#ASD 是允许的,但是 @#$ ^& 是不允许的。我需要RegEx进行此验证。

How to put a validation over a field which wouldn't allow only special characters, that means AB#,A89@,@#ASD is allowed but @#$^& or # is not allowed. I need the RegEx for this validation.

推荐答案

str.match(/^[A-Z#@,]+$/)

将匹配一个字符串......

will match a string that...


  • ...开始 ^ 并以附带的模式结束 $

  • ...包含任何大写字母 AZ (不符合小写字母)

  • 。 ..仅包含特殊字符 @

  • ...至少有1个字符(没有空字符串)

  • ... starts ^ and ends $ with the enclosed pattern
  • ... contains any upper case letters A-Z (will not match lower case letters)
  • ... contains only the special chars #, @, and ,
  • ... has at least 1 character (no empty string)

For不区分大小写,您可以在最后添加 i :( ig / pattern / i

For case insensitive, you can add i at the end : (i.g. /pattern/i)

** 更新 **

如果您需要验证该字段是否仅包含特殊字符,可以检查字符串是否只包含非单词或数字的字符:

If you need to validate if the field contains only specials characters, you can check if the string contains only characters that are not words or numbers :

if (str.match(/^[^A-Z0-9]*$/i)) {
   alert('Invalid');
} else {
   alert('Valid');
}

这将匹配仅包含非字母数字字符的字符串。空字符串也会产生无效。用 + 替换 * 以允许空字符串有效。

This will match a string which contains only non-alphanumeric characters. An empty string will also yield invalid. Replace * with + to allow empty strings to be valid.

这篇关于如何使用正则表达式检查用户输入是否仅包含特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆