2017-04-06 70 views
0

我使用Javascript来验证模式,我基本上只是想让字母数字值和标点符号。奇怪的是,当我输入一个(或一个)紧跟其后的东西时,它会失败,但如果我给它一个空间它的工作。我究竟做错了什么?奇怪的正则表达式问题

$(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 
+3

通行证都在这里。您能否使用片段功能提供完整的交互式示例?另外,如果你用“just”表示整个字符串,你需要将它锚定到起始位置并允许多个字符,所以'/^[A-Za-z0-9 _。,!'''] + $ /'。或者对于否定测试,'/ [^ \ w。,!''] /'。 – Ryan

+0

已添加完整的代码块 – p0tta

回答

-1

/^[A-Za-z0-9 _.,!"']$/g;而已。

+3

请考虑编辑您的答案以包含解释。 – gyre

0

下面是如何解决你的问题 - 有一些差异,但你应该能够复制粘贴到你的代码。

的jsfiddle:https://jsfiddle.net/pg792z79/

<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> 
+0

这个正则表达式总是会给出肯定的响应,因为该模式在字符串中的任何位置范围内有零个或多个有效字符满足。 – mickmackusa

+0

哦,这很奇怪,它为我工作。让我看看我能否修复它... – Qhuea

1

您当前的模式只检查字符串中的最后一个字符。

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

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

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

第一种是最简单的(我的偏好),二是可能是最可读的,第三个是使用unicode,是最难理解。一切都会很快,所以速度并不是真正的标准。

这是一个JSFiddle Demo与一些改进和意见建议。

HTML:

<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", "123456789" --> 
<!-- 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. --> 

CSS:

#comment{ 
    width:200px; 
} 
#commentError{ 
    display:none; 
    width:400px; 
} 

JS:

$(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(); 
    } 
});