简体   繁体   中英

Javascript Regular Expression that diallows special characters

I have the below 3 function. 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 ; 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:

/^[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. I'm not sure what that entails in Javascript but my guess is that it's probably not value == null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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