How do I make the Caps Lock key warning activated?

9

How do I make a warning when the Caps Lock key is enabled in the password field?

At first I would like solutions in pure JavaScript, but using jQuery and related will be accepted.

    
asked by anonymous 10.05.2017 / 19:29

3 answers

10

Use getModifierState('CapsLock') in an event to detect the state. Functional example below:

document.addEventListener('keydown', function( event ) {
  var flag = event.getModifierState && event.getModifierState('CapsLock');
  console.log( flag ? "Caps Lock ON": "Caps Lock OFF");
});
Clique nesta área e pressione Caps Lock.

All modern browsers (with the exception of Opera Mini) support this method:

Source.

    
10.05.2017 / 20:17
2

The logic behind this is simple: check if the letter you typed is uppercase, and if the shift is not pressed:

document.getElementById('txtSenha').onkeyup = function (e) {

  var key = e.charCode || e.keyCode;
  
  //enter, caps lock e backspace não interessam
  if(key == 13 || key == 8 || key == 46 || key == 20){
    return false;
  }
  
  //pega o último caracter digitado
	var tamanho = this.value.length
	var ultimo_caracter = this.value.substring(tamanho - 1);
  
  //Verifica se é maiúsculo, e se não é shift
  if(ultimo_caracter.toUpperCase() == ultimo_caracter 
  && ultimo_caracter.toLowerCase() != ultimo_caracter
  && !e.shiftKey)
  {
  	alert('Caps Lock está pressionado!');
  }
};
<input type="password" id="txtSenha" />

This example does not use JQuery. You can also customize, allow or block more keys, but I would do something similar to that myself

    
10.05.2017 / 19:42
0

You can use toUpperCase() of JavaScript to know if the letter is in uppercase, when the keypress of Jquery event is called.

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
        alert('caps is on');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="password" id="example" />

For more information:

toUpperCase () : link

toLowerCase () : link

Original response in English: link

    
06.07.2017 / 23:40