-2

I want the user to only be able to enter English characters, the code below works but on a mac if you hold the letter "a" for example you can insert accented characters such as "á". I've tried a few different approaches with keydown, keyup etc but even on the release of the key it thinks the value that was entered is "A" so it gets past the regex. Anyone know whats going wrong or a better way on how to do this please?

$('.monogram-letters').on("keypress", function(e) {
    var englishAlphabet = /[A-Za-z]/g;
    var key = String.fromCharCode(e.which);

    if (englishAlphabet.test(key)) {
        console.log('true');
        return true;

    } else {
        console.log('false');
    }

    return false;
});


$('.monogram-letters').on("paste", function(e) {
    e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="" class="monogram-letters valid" maxlength="3" id="options-41-container" name="options[41]" data-category="41" data-val="type your letters (up to 3)" required="" aria-required="true" aria-invalid="false">
Liam
  • 27,717
  • 28
  • 128
  • 190
NoDachi
  • 874
  • 4
  • 10
  • 20

2 Answers2

-1

You can instruct an input text to accept only english characters doing so:

<input pattern="[a-z]" />

You will want to validate server-side as well obviously.

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160
-2

The solution I ended up going for was to check the final string and then just emptying the input if it had an accented character

    var $monogramInput = $('.monogram-letters');
    var englishAlphabet = /^[a-z]+$/i;

     $monogramInput.on("keypress", function(e) {
        var key = String.fromCharCode(e.which);

        if(englishAlphabet.test(key)) {
            return true;
        }
        return false;

    }).blur(function() {
        var enteredValue = $(this).val();

       if(!enteredValue.match(englishAlphabet)) {
            $(this).val('');
        }
    });
NoDachi
  • 874
  • 4
  • 10
  • 20