Type only letters and dots

Asked

Viewed 8,159 times

0

I’m developing a page with a login and password that searches the data in the company’s AD. I am using PHP and need to somehow allow only letters and dot (.) in the login field. I’m using the script below, it’s very basic but it works in parts. When I enter a number, it appears in the field, even using onkeypress or onkeyup. Is there any way for it to block even, nor appear in the field the invalid character?

function somente_letras(campo){
    var digits="abcdefghijklmnopqrstuvwyxz.";
    var campo_temp;
       for (var i=0;i<campo.value.length;i++){
          campo_temp=campo.value.substring(i,i+1);
              if (digits.indexOf(campo_temp)==-1){
                campo.value = campo.value.substring(0,i);
                return false;
              }
        }
}

  • which means invalid character in this context?

  • Numbers, accented letters and other symbols, except the point (.). Only this would be "valid" in the context of the page: digits="abcdefghijklmnopqrstuvwyxz."

  • http://www.w3schools.com/jsref/event_onkeydown.asp onkeydown.

2 answers

5

See if this function works the way you need it:

function somente_letras() {
    this.value = this.value.replace(/[^\w\.]|\d/g, '');
};

Where:

document.getElementById("campo").onkeyup = somente_letras;

Fiddle

One problem with this way of filtering the characters in the field is that the keyboard control keys also do not work, such as the arrow keys, Ctrl+A or Home and End. For the arrow keys it is possible to detect the key code with that if:

var code = (e.keyCode || e.which);

// do nothing if it's an arrow key
if(code == 37 || code == 38 || code == 39 || code == 40) {
    return;
}

Fiddle

  • He preferred using jquery. The more pure javascript, the better.

  • @Eduardoseixas I did not use jQuery because in his code there was no and the tag was not used, but anyway...

3


Can do using regular expression [a-zA-Z.], thus:

jQuery('.meucampo').keyup(function () { 
    this.value = this.value.replace(/[^a-zA-Z.]/g,'');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="meucampo" value="" />

  • 1

    exactly, with your idea worked. Thank you.

  • Friend how do I make so that when I give "space" it gives the "space" and does not erase the "space"? I want to put it in an input where the person type her name.

Browser other questions tagged

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