2017-09-25 89 views
-3

我有下面的3個函數。 我似乎無法得到正確的正則表達式 請幫助我JavaScript正則表達式,用於撥號特殊字符

//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(/^[[email protected]]+$/) == null) { 
      txtName.value = txtName.value.replace(/[\W-]/g, ''); 
     } 
    } 
+0

你在哪個問題?在所有這些? – DontVoteMeDown

+0

究竟是什麼「特殊字符」?例如爲什麼'@'不是特殊字符,而是'&'是? – Liam

+0

'[^ a-zA-Z0-9 \ @ \ s \。\ _ \ - ]'匹配除a-z,A-Z,0-9,@, (空白區域)以外的任何內容。 (點),_和 - ,這是你想要的嗎? –

回答

0

你不寫正則表達式來「防止」的東西;他們不是黑名單,而是白名單。所以,如果有人發送一個你不想要的字符,那是因爲你的正則表達式允許它們。我對你的具體問題的猜測與.-_部分有關。在正則表達式中,X-Y表示「從X到Y的所有內容」,所以這將轉化爲「從ASCII(2E)到_(ASCII 5F)」的所有內容,具有諷刺意味的是包括所有大寫和小寫字母,數字0到9,/:;@只是僅舉幾例。爲了避免這種情況,你可能應該將這部分改爲:.\-_,因爲斜槓會逃離破折號。然而,這仍然會讓你的用戶進行的名字,如.Bob-Larry,你可能不希望這讓你的正則表達式也許應該閱讀:

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

這將需要第一個字符是字母,數字和任何其餘爲字母數字,.-_

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

相關問題