Enter only letters and periods

0

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

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;
              }
        }
}
    
asked by anonymous 28.08.2015 / 19:35

2 answers

2

You can do this using the regular expression [a-zA-Z.] , like this:

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><inputtype="text" class="meucampo" value="" />
    
28.08.2015 / 19:49
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

A 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. 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

    
28.08.2015 / 19:47