簡體   English   中英

不允許特殊字符的 Javascript 正則表達式

[英]Javascript Regular Expression that diallows special characters

我有以下 3 個功能。 我似乎無法得到正確的正則表達式 請幫助我

    //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, '');
        }
    }

您不會編寫正則表達式來“防止”某些事情; 他們不是黑名單,而是白名單。 因此,如果有人發送了您不想要的字符,那是因為您的正則表達式允許他們這樣做。 我對您的具體問題的猜測與.-_部分有關。 在正則表達式中, XY表示“從 X 到 Y 的所有內容”,因此這將轉換為“從 .(ASCII 2E)到 _(ASCII 5F)的所有內容”,具有諷刺意味的是,它包括所有大寫和小寫字母、數字 0 到 9、 / , : , ; @只是僅舉幾例。 為避免這種情況,您可能應該將這部分更改為: .\\-_因為斜杠將轉義破折號。 但是,這仍然會讓您的用戶使用.Bob-Larry類的名稱,並且您可能不想要這樣,因此您的正則表達式可能應該是:

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

這將要求第一個字符為字母數字,其余任何字符為字母數字,即. -_

您還需要檢查您的值是否與此 reg-ex 匹配而不是不匹配。 我不確定 Javascript 中的含義,但我的猜測是它可能不是value == null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM