您当前的模式只检查字符串中的最后一个字符。
您将需要一个检查整个字符串的模式。这是通过使用^
和$
锚并使用一个或多个量词*
(假设注释是可选的)来实现的。
你的正则表达式模式可以是:
/^[\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();
}
});
通行证都在这里。您能否使用片段功能提供完整的交互式示例?另外,如果你用“just”表示整个字符串,你需要将它锚定到起始位置并允许多个字符,所以'/^[A-Za-z0-9 _。,!'''] + $ /'。或者对于否定测试,'/ [^ \ w。,!''] /'。 – Ryan
已添加完整的代码块 – p0tta