简体   繁体   English

使用jQuery仅以输入形式禁用标签和数字

[英]Disable tags and numbers alone in input form with jQuery

I have a form and I would like to disable < > # @ and numbers alone ('test 123' should work). 我有一个表格,我想单独禁用< > # @和数字(“ test 123”应该起作用)。

For the first condition I tried 对于第一个条件,我尝试了

if ( $(this).val().match("^[^>#<@*]+$") ) { // todo }

But it matches everytime.. 但是每次都匹配。

I have already checked on Stackoverflow, W3Schools etc but I don't know why I cannot apply the regex 我已经检查过Stackoverflow,W3Schools等,但是我不知道为什么我不能应用正则表达式

Thank you 谢谢

If I understand correctly, you want to match string with at least one character that is not a digit and without the following characters : <, >, # and @ 如果我理解正确,则希望将字符串与至少一个不是数字的字符匹配,并且不包含以下字符: <, >, # and @
You can do that with this regex : 您可以使用此正则表达式执行此操作:
(?=.*\\D)[^<>#@]*

Try below: using RegExp object you can test the pattern as shown below 请尝试以下操作:使用RegExp对象,您可以测试模式,如下所示

var regEx = new RegExp("[0-9a-zA-Z\\s]+"); 
if ( regEx.test($(this).val()) ) 

You need to add a negative lookbehind to the pattern you used and define the regex like 您需要在所使用的模式后添加负向后看,并定义正则表达式,例如

/^(?!\d+$)[^>#<@*]+$/

See the regex demo (note \\n is added since the demo input string contains line breaks). 请参阅regex演示 (由于演示输入字符串包含换行符,因此添加了\\n注意)。

Details : 详细资料

  • ^ - start of string ^ -字符串的开头
  • (?!\\d+$) - the input string cannot consist of only 1+ digits (?!\\d+$) -输入字符串不能仅包含1个以上的数字
  • [^>#<@*]+ - 1 or more chars other than > , # , < , @ , * [^>#<@*]+ - >#<@*以外的1个或多个字符
  • $ - end of string. $ -字符串结尾。

Use it with a RegExp#test to only return true or false (with String#match , there is unnecessary overhead related to returning all the array with values that you do not need here): 将它与RegExp#test一起使用只能返回truefalse (使用String#match ,与返回具有此处不需要的值的所有数组有关的不必要的开销):

if (/^(?!\d+$)[^>#<@*]+$/.test($(this).val())) {....} 

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

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