尝试验证我的表单并为无效字符设置变量,但我无法识别它们,因为它们只是一堆符号? -
function validation(){
var Name =
document.getElementById("name").value;
var Email = document.getElementByID("email").value;
var invalidSymbol = /[\~\`\!\#\$\%\^\&\*\(\)\-\+\{\}\:\\\;\"\'\<\>\?\,\]/;
if Name == ""{
alert("Please enter your name");
document.getElementById("Name").focus();
return false;
}else if (Email == "" | | Email.indexOf("@")<1 || Email.lastIndexOf("@")+2 || Email.lastIndexOf(".")+2>=Email.indexOf("@").length || Email.match(invalidSymbol)){
alert ("Please enter a valid e-mail address");
document.getElementById("email").focus();
return false;
}else{
return true;
}
}
最佳答案
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).
如此处所述: javascript regexp remove all special characters 经过 annakata
关于javascript - JS表单验证,无效字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41052421/