How do I activate the Caps Lock key warning?

Asked

Viewed 2,079 times

9

How to make a warning for 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.

  • 2

    http://stackoverflow.com/questions/348792/how-do-you-tell-if-caps-lock-is-using-javascript this link helped me once..

  • Forgive my ignorance, but it would not be wiser and less laborious to create a function that would put all the high box characters in low box?

  • Felix, but doing so decreases the strength of the password. If it were to any other field could be valid even do so.

3 answers

10


Utilize 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 (except Opera Mini) support this method:inserir a descrição da imagem aqui

Source.

2

The logic behind this is simple: check if the typed letter is uppercase, and if 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

  • because he wants in javascript

  • 1

    That’s right, I did.

0

You can use toUpperCase() Javascript to know if the letter is capitalized, when the event keypress of Jquery 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>
<input type="password" id="example" />

For more information:

toUpperCase(): https://www.w3schools.com/jsref/jsref_touppercase.asp

toLowerCase(): https://www.w3schools.com/jsref/jsref_tolowercase.asp

Original response in English: https://stackoverflow.com/a/896515/6647038

Browser other questions tagged

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