2017-09-25 91 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

相关问题