Javascript 无法验证连字符
我正在尝试验证包含“字母数字字符、支持的符号和空格”的名称。这里我只需要允许一个Javascript 无法验证连字符,javascript,jquery,regex,Javascript,Jquery,Regex,我正在尝试验证包含“字母数字字符、支持的符号和空格”的名称。这里我只需要允许一个连字符(-),但不允许双连字符(-) 这是我的代码,如下所示: $.validator.addMethod( 'alphanumeric_only', function (val, elem) { return this.optional(elem) || /^[^*~<^>+(\--)/;|.]+$/.test(val); }, $.format("shouldn't conta
连字符(-)
,但不允许双连字符(-)
这是我的代码,如下所示:
$.validator.addMethod(
'alphanumeric_only',
function (val, elem) {
return this.optional(elem) || /^[^*~<^>+(\--)/;|.]+$/.test(val);
},
$.format("shouldn't contain *.^~<>/;|")
);
$.validator.addMethod(
“仅字母数字”,
函数(val,elem){
返回此.optional(elem)| |/^[^*~+(\--)/|.]+$/.test(val);
},
$.format(“不应包含*.^ ~/;|”)
);
上面的代码甚至不允许一个
连字符(-)
。如何允许使用单连字符,但防止使用双连字符。非常感谢您的帮助。为此,您需要一张底片:
/^(?。*--)[^*~+()\/.]+$/
我应该这样做
说明:
^ # Start of string
(?! # Assert it's impossible to match the following:
.* # any string, followed by
-- # two hyphens
) # End of lookahead
[^*~<^>+()\/;|.]+ # Match a string consisting only of characters other than these
$ # End of string
^#字符串的开头
(?!#断言不可能匹配以下内容:
.*#任意字符串,后跟
--#两个连字符
)#展望结束
[^*~+()\/;|.]+#匹配仅由以下字符以外的字符组成的字符串
$#字符串末尾
并不是说,如果字符串可以包含换行符,则此操作可能会失败。如果可以,请使用
/^(?![\s\S]*--)[^*~<^>+()\/;|.]+$/
/^(?![\s\s]*--)[^*~+()\/;|]]+$/
我建议您使用白名单而不是黑名单。然而,这是可行的:
<input type="text" id="validate"/>
<script>
$('#validate').keyup(function(){
val = this.value;
if(/([*.^~<>/;|]|--)/.test(val)) this.style.backgroundColor='red';
else this.style.backgroundColor='';
});
</script>
$(“#验证”).keyup(函数(){
val=该值;
如果(/([*.^~/|]|--)/.test(val))此.style.backgroundColor='red';
否则这个.style.backgroundColor='';
});
@core-感谢您的友好回复。
<input type="text" id="validate"/>
<script>
$('#validate').keyup(function(){
val = this.value;
if(/([*.^~<>/;|]|--)/.test(val)) this.style.backgroundColor='red';
else this.style.backgroundColor='';
});
</script>