简体   繁体   中英

RegExp for current character JavaScript

I'm trying to validate a character to make sure it's a letter (not a number, symbol, etc.) BEFORE it's allowed to be entered into the form field. How can I do that with JavaScript?

Here is something I tried:

<script type="text/javascript">

function checkTest() {
    var letterValue = document.forms[0].test.value;
    var letterCheck = /[a-z]/i;
    var letterTest = letterValue.test(letterCheck);

}

</script>
<html>
    <body>
        <form>
            <input type="text" name="test" onkeypress="checkTest();"/>
        </form>
    </body>
</html>

This code will check the string of the value. I've tried using var letterLeng= letterValue.length and then using var letterChar = letterValue.charAt(letterLeng) or even var letterChar = letterValue.charAt(letterLeng - 1) and all to no avail. Any advice would be much appreciated.

Ask the event for the key that was pressed then test it:

 function checkTest(event) { event = event || window.event; if (!/[A-Za-z]/.test(String.fromCharCode(event.keyCode || event.which))) { if (event.preventDefault) event.preventDefault(); else event.returnValue = false; } } 
 <input type="text" name="test" onkeypress="checkTest(event);"/> 

I like Alex K's answer, but I could not get the 'onkeypress' handler to work so I tried something using Jquery. It doesn't keep the bad letters from appearing briefly, but it does keep them from being entered.

It uses the 'keyup' event, which actually makes checking for the key code much easier in this instance since you want to limit it to [a-zA-Z]

$("#myinput").on("keyup", function (e) {
    // Ignore the shift key.
    if (e.keyCode === 16) {
        return true;
    }

    if ((e.keyCode < 65 || e.keyCode > 90)) {
        var str = $("#myinput").val();
        $("#myinput").val(str.slice(0, str.length - 1));
    }
});

The working fiddle is here: http://jsfiddle.net/yaa9snce/

What you are looking for is the onkeypress event.

 <input type="text" onkeypress="myFunction()"> <script> function myFunction() { alert("You pressed a key inside the input field"); } </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM