Javascript 奇怪的正则表达式问题

Javascript 奇怪的正则表达式问题,javascript,regex,Javascript,Regex,我正在使用Javascript来验证一个模式,我基本上希望只允许字母数字值和标点符号。奇怪的是,当我进入a(或a)后紧接着是某个东西时,它失败了,但如果我给它一个空间,它就会工作。我做错了什么 $(document).on('blur', '#comment', function () { var rgx = /[A-Za-z0-9 _.,!"']$/; var value = $(this).val(); if (!rgx.test(value) == tr

我正在使用Javascript来验证一个模式,我基本上希望只允许字母数字值和标点符号。奇怪的是,当我进入a(或a)后紧接着是某个东西时,它失败了,但如果我给它一个空间,它就会工作。我做错了什么

$(document).on('blur', '#comment', function () {
      var rgx = /[A-Za-z0-9 _.,!"']$/;
      var value = $(this).val();
      if (!rgx.test(value) == true){
          $("#comment").focus();
          $("#commentError").val("Please use only alphabets, numbers and punctuations");
      }else{
        $("#commentError").val("");
      }
  });
测试用例:

冒充

Input: ( a
失败于

Input: (a

/^[A-Za-z0-9 u.,!“']$/g
;就是这样。

以下是解决问题的方法-有一些不同之处,但您应该能够将其复制粘贴到代码中

JSfiddle:



var str=“apples”/当前模式仅检查字符串中的最后一个字符

您需要有一个模式来检查整个字符串。这是通过使用
^
$
锚和使用一个或多个量词
*
(假设注释是可选的)来实现的

您的正则表达式模式可以是:

/^[\w.,!”]*$/
/^[A-Z0-9,!”]*$/i
/^[u20-u22u27u2Cu2Eu30-u39u41-u5Au5F]*$/i

第一个是最简短的(我的偏好),第二个可能是最可读的,第三个是使用,也是最难理解的。所有这些都很快,所以速度并不是一个真正的标准

这里是一个有一些改进和评论的建议

HTML:

JS:


这里两个都通过。请使用snippet功能包含一个完整的交互式示例好吗?另外,如果“just”是指整个字符串,则需要将其锚定到开头并允许使用多个字符,因此
/^[a-Za-z0-9 u.,!“]+$/
。或者对于一个否定的测试,<代码> /[^ \w,!] ] /<代码>。添加完整的代码块,请考虑编辑你的答案以包含一个解释。这个ReGEX模式总是给出一个积极的响应,因为模式在字符串中的任何地方的零个或多个有效字符满足。
<script>
    var str = "apples" // <-- this is your input string
    var patt = new RegExp('[A-Za-z0-9 _.,!"\'/$]*');
    if(patt.test(str)) {
        //success
        $("#commentError").val("");
    } else {
        //error - did not match regex
        $("#comment").focus();
        $("#commentError").val("Please use only alphabets, numbers and punctuations");
    }
</script>
<input id="comment" name="comment" value="( a">
<i> press tab to trigger validation</i><br>
<input id="commentError" value="Comment Limit: 25. Use only letters, numbers, and  punctuation.">

<!-- I have added "?" to your regex pattern because it seems permissible. -->
<!-- Invalid values: "(a", "( a", "12345678901234567890123456" -->
<!-- Valid values: "", "Hello World", "l0ts, "of go.od' st_uff!?" -->

<!-- Additional advice: if you are storing the input value in a database table,
     you should limit the field length to what the table column can hold.
     If, per se, you are saving as VARCHAR(255), then set the #comment field limit
     as 255 so that the value isn't truncated during saving. -->
#comment{
    width:200px;
}
#commentError{
    display:none;
    width:400px;
}
$(document).on('blur','#comment',function(){
    // no variable declaration needed
    if(/^[\w .,!"'?]{0,25}$/.test($(this).val())){  // contains only valid chars w/ limit
        $("#commentError").hide();
    }else{
        $("#comment").focus();  // disallows focus on any other field
        $("#commentError").show();
    }
});