简体   繁体   English

不允许特殊字符的 Javascript 正则表达式

[英]Javascript Regular Expression that diallows special characters

I have the below 3 function.我有以下 3 个功能。 I cant seem to get the right regular expression Please assist me我似乎无法得到正确的正则表达式 请帮助我

    //Allow Alphanumeric,dot,dash,underscore but prevent special character and space
    function Usernames(txtName) {
        if (txtName.value != '' && txtName.value.match(/^[0-9a-zA-Z.-_]+$/) == null) {
            txtName.value = txtName.value.replace(/[\W- ]/g, '');
        }
    }
    //Allow Alphanumeric,dot,dash,underscore and space but prevent special characters
    function Fullnames(txtName) {
        if (txtName.value != '' && txtName.value.match(/^[a-zA-Z0-9. -_]+$/) == null) {
            txtName.value = txtName.value.replace(/[\W-]/g, '');
        }
    }
    //Allow Alphanumeric,dot,dash,underscore the "@" sign but prevent special character and space
    function Email(txtName) {
        if (txtName.value != '' && txtName.value.match(/^[a-zA-Z0-9.-_@]+$/) == null) {
            txtName.value = txtName.value.replace(/[\W-]/g, '');
        }
    }

You don't write regular expressions to "prevent" something;您不会编写正则表达式来“防止”某些事情; they're not blacklists but whitelists.他们不是黑名单,而是白名单。 So, if someone is sending in a character that you don't want it's because your regex allowed them to.因此,如果有人发送了您不想要的字符,那是因为您的正则表达式允许他们这样做。 My guess as to your specific problem has to do with the .-_ part.我对您的具体问题的猜测与.-_部分有关。 In regex's, the XY means "everything from X to Y" so this would translate to "everything from . (ASCII 2E) to _ (ASCII 5F)" which ironically includes all uppercase and lowercase letters, the numbers 0 to 9, the / , the : , the ;在正则表达式中, XY表示“从 X 到 Y 的所有内容”,因此这将转换为“从 .(ASCII 2E)到 _(ASCII 5F)的所有内容”,具有讽刺意味的是,它包括所有大写和小写字母、数字 0 到 9、 / , : , ; and the @ just to name a few.@只是仅举几例。 To avoid this, you should probably change this part to be: .\\-_ as the slash will escape the dash.为避免这种情况,您可能应该将这部分更改为: .\\-_因为斜杠将转义破折号。 However, that'll still let your users make names like .Bob or -Larry and you probably don't want this so your regex should probably read:但是,这仍然会让您的用户使用.Bob-Larry类的名称,并且您可能不想要这样,因此您的正则表达式可能应该是:

/^[0-9a-zA-Z][0-9a-zA-Z.\-_]*$/

This will require the first character to be alphanumeric and any of the remainder to be alphanumeric, the .这将要求第一个字符为字母数字,其余任何字符为字母数字,即. , the - or the _ . -_

You'll also want to check that your value matches this reg-ex instead of not.您还需要检查您的值是否与此 reg-ex 匹配而不是不匹配。 I'm not sure what that entails in Javascript but my guess is that it's probably not value == null我不确定 Javascript 中的含义,但我的猜测是它可能不是value == null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM