开发者

Javascript special character validation

开发者 https://www.devze.com 2023-03-29 20:16 出处:网络
<script language=\"JavaScript\"> var mikExp = /[$\\\\@\\\\\\#%\\^\\&\\*\\(\\)\\[\\]\\+\\_\\{\\}\\`\\~\\=\\|]/;
<script language="JavaScript">
var mikExp = /[$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|]/;
function dodacheck(val) 
{
    var strPass = val.value;
    var strLength = strPass.length;
    var lchar = val.value.charAt((strLength) - 1);
    if(lchar.search(mikExp) != -1) 
    {
        var tst = val.value.substring(0, (strLength) - 1);
        val.value = tst;
    }
}
<开发者_运维知识库/script>

<input type="text" name="display1" id="display1" value="<?php echo $wc['display1']; ?>" class="width241 input fnt11" onKeyUp="javascript:dodacheck(xyz.display1);" maxlength="20">

This function makes sure that special characters are not printed in a input box. But when i press shift and press any special characters for more than 5 seconds its prints the special characters.

Any clues how to stop it from happening?


Try This,

var mikExp = /[$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|]/;

    function check(e) {
    var keynum
    var keychar
    var numcheck
    // For Internet Explorer
    if (window.event)
    {
    keynum = e.keyCode
    }
    // For Netscape/Firefox/Opera
    else if (e.which)
    {
    keynum = e.which
    }
    keychar = String.fromCharCode(keynum)
    if ((keychar.toString()).search(mikExp) == 0)
    {

    return false;
    }
    else {
    return true;
    }
    }

    <input type="text" name="display1" id="display1" value="" class="width241 input fnt11" onKeypress="javascript:return check(event);"  maxlength="20">


You should try with onKeyDown because it triggers when user hits the keys, not when it releases them.

So input should become

<input type="text" name="display1" id="display1" value="<?php echo $wc['display1']; ?>" class="width241 input fnt11" onKeyDown="javascript:dodacheck(xyz.display1);" onKeyUp="javascript:dodacheck(xyz.display1);" maxlength="20">

I've added onKeyUp also for extra measure :)

0

精彩评论

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