2

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.

turd.ferguson
  • 51
  • 1
  • 1
  • 8

3 Answers3

1

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);"/>
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

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/

HeadCode
  • 2,770
  • 1
  • 14
  • 26
-1

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>
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • I meant to include that in my code. My mistake. Even with me doing that, I can't get the regexp to check the current character that is typed. It's always checking one step behind. – turd.ferguson Nov 05 '14 at 17:17
  • @turd.ferguson Thats because the key hasn't been typed yet. When you grab the value form the form, it still doesn't have the character. What you need to do is use a more advanced event listener. See http://unixpapa.com/js/testkey.html – David says Reinstate Monica Nov 05 '14 at 17:21