最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use regex to check that user input does not consist of special characters only? - Stack Overflow

programmeradmin6浏览0评论

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.

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.

Share Improve this question edited Nov 16, 2014 at 3:45 user3717023 asked Sep 6, 2010 at 6:56 ArkoArko 1081 gold badge1 silver badge8 bronze badges 3
  • 2 this has nothing to do with jQuery, you mean javascript ? – Yanick Rochon Commented Sep 6, 2010 at 6:59
  • 5 Nono... JavaScript has been renamed to jQuery, didntchya know? – mpen Commented Sep 6, 2010 at 7:50
  • @OP: You might want to take a look at bassistance.de/jquery-plugins/jquery-plugin-validation and stackoverflow./questions/280759/… – mpen Commented Sep 6, 2010 at 7:51
Add a ment  | 

3 Answers 3

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

will match a string that...

  • ... 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 case insensitive, you can add i at the end : (i.g. /pattern/i)

** UPDATE **

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.

If you can use a "negative match" for your validation, i. e. the input is OK if the regex does not match, then I suggest

^\W*$

This will match a string that consists only of non-word characters (or the empty string).

If you need a positive match, then use

^\W*\w.*$

This will match if there is at least one alphanumeric character in the string.

I believe what you're looking for is something like this:

!str.match(/^[@#$^&]*$/)

Checks that the string does not contain only symbols, i.e., it contains at least one character that isn't a symbol.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论