\', \'|\' I am quite new to this a" />
开发者

Regular expression for not allowing some special characters

I want to write a regular expression for allowing alphanumeric values and special characters except the ones mentioned here '`', '^', '=', '"', '<', '>', '|' I am quite new to this and not really getting how to do it. I am trying something like below:

function dbaNameCheck(input, regex) 
{
  if (regex && input.value.length > 0)
   {
    if(regex.match(/dbaNameCheck/i) && input.value.match(/[0-9A-Za-z]|[\`\^\=\"\<\>\|]*/g))   
     {
         input.value = input.value.replace(/[\`\^\=\"\<\>\|]*/g, '');
         input.focus();
     }
   }
}

I am calling this function like this on keypress event:

onkeypress="dbaNameCheck(this,'dbaNameCheck');"

But it's not working as expected. The values in my textbox can be alphanumeric and any special character except the 开发者_StackOverflow中文版one mentioned above. Can someone help me with this?


Rewrite your function like this:

function dbaNameCheck(input) 
{
    var re = /[`\^="<>|]+/g;

    if (input.value.length > 0 && re.test(input.value))   
    {
        input.value = input.value.replace(re, '');
        input.focus();
    }
}

Then call it this way:

onkeyup="dbaNameCheck(this);"

onKeyup is the event you want to catch, instead of onKeypress.


/[^`^="<>|]/ should match everything except for those characters. the first ^ means "anything but the following characters".


but if you're going to replace those with the empty string, you probably don't want the ^ first.

'|||abc<==<<<'.replace(/[<>|]/g, '')

gives "abc==="


FYI, here is another (old-school) way to achieve what you wanted to do, without using regex. However, if can't deal with copy-and-paste.

First declare your function like

function killKeys(e)
{
    switch(e.charCode)
    {
    case 60: // "<"
    case 61: // "="
    case 62: // ">"
    case 94: // "^"
    case 96: // "`"
        return false;
        break;
    default:
        return true;
    }
}

Then call it like this

onkeypress="return killKeys(event);


<script language="javascript" type="text/javascript">
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 97 || charCode > 122) && (charCode < 65 || charCode > 96) && (charCode < 48 || charCode > 57) || charCode == 110 || charCode == 190)
            return false;
        return true;
    }    
</script>

<asp:TextBox  ID="txtCompany" runat="server" onkeypress="return isNumberKey(event)" ></asp:TextBox>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜