javascript - JS表单验证,无效字符?

标签 javascript validation

尝试验证我的表单并为无效字符设置变量,但我无法识别它们,因为它们只是一堆符号? -

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/

相关文章:

javascript - 为什么我的 javascript 时钟不工作?

javascript - 如何使用javascript同时触发回车键和按钮

django - 如何处理 Django 验证错误

ruby-on-rails - Rails 3 : Why integer field is not validated against regex?

javascript - 使用 jquery 在表列中添加美元金额

javascript - 有没有办法检测可观察对象的嵌套结构的任何元素是否已更改?

javascript - Highcharts.js : get specific value from data to tooltip

java - Jackson 验证输入 json 对象

ruby-on-rails-3 - 仅当不为空时才验证电子邮件格式 Rails 3

validation - Angular2/ Material 2 : md-input-container label is not resetting float when value is changed programmatically