Mask to only allow letters and letters to be inserted with accents

Asked

Viewed 329 times

0

Good morning, I wanted a mask for a text box where the user can only insert letters and letters with accents.

The code I could find just lets you insert letters without accents.

function lettersOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
    if (charCode == 32)
        return true;
    if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
        return false;
    }
    else
        return true;
}

The variable 'evt' is the letter pressed, that is, in the textbox I am using the property onkeypress="return lettersOnly(event)".

  • Friend, you can use REGEX, follow the link to help: https://stackoverflow.com/questions/3617797/regex-to-match-only-letters

2 answers

0

You can use this imaskjs plugin

var regExpMask = IMask(
  document.getElementById('regexp-mask'),
  {
    mask: /^[a-zöüóőúéáàűíÖÜÓŐÚÉÁÀŰÍçÇ]{0,100}$/
  });
<script src="https://unpkg.com/imask"></script>
<input type="text" value="" id="regexp-mask">

0

Just a simple .test with a regex and a flag i (of case insensitive, either in upper or lower case):

function lettersOnly(evt) {
   if(!/[a-záéíóúàèìòùãõâêîôûäëïöüç]/i.test(evt.key)) return false;
}
<input type="text" onKeyPress="return lettersOnly(event)">

regex will validate all letters of a to z (upper or lower case) and all accented letters áéíóúàèìòùãõâêîôûäëïöüç (upper or lower case).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.