特殊字符验证 [英] Special character validation
问题描述
我写了一些JavaScript来验证字符串是字母数字,但我只是想知道如何添加一些代码来包含连字符( - )和斜线(/)作为可接受的输入。这是我现在的代码:
$ b $ pre $ function validateAddress(){
var address = document.getElementById('address') ;
if(address.value ==){
alert(Address must be filled out);
返回false;
} else(document.getElementById('address').value.length> 150){
alert(地址不能超过150个字符);
返回false;
} else if(/[^a-zA-Z0-9\-\\\/]/.test(address)){
alert('地址只能包含字母数字字符,连字符( - )和反斜杠(\)');
返回false;
$ / code $ / pre
将它们添加到字符组中。当然,因为 I have some javascript written to validate that a string is alphanumeric but i was just wondering how i could add some code to include hyphens(-) and slash's(/) as acceptable inputs. Here is my current code:
Simply add them to the character group. Of course, because both
这篇关于特殊字符验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! -
和 /
在这个上下文中是特殊字符( /
结束RegExp,
-
表示一个范围),您需要使用前面的 \
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $变量TCode = document.getElementById('address')。value ; ($ [
$ b $ if(/ [^ a-zA-Z0-9\ -\ /] /。test(TCode)){
alert('Input is not alphanumeric');
返回false;
}
返回true;
}
function validateAddress() {
var address = document.getElementById('address');
if (address.value == "") {
alert("Address must be filled out");
return false;
} else if (document.getElementById('address').value.length > 150) {
alert("Address cannot be more than 150 characters");
return false;
} else if (/[^a-zA-Z0-9\-\/]/.test(address)) {
alert('Address can only contain alphanumeric characters, hyphens(-) and back slashs(\)');
return false;
}
}
-
and /
are special characters in this context (/
ends a RegExp, -
expresses a range), you'll need to escape them with a preceding \
:function validateAddress(){
var TCode = document.getElementById('address').value;
if( /[^a-zA-Z0-9\-\/]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}