How do you tell if caps lock is on using JavaScript? - javascript

How do you tell if caps lock is on using JavaScript?
One caveat though: I did google it and the best solution I could find was to attach an onkeypress event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... wasteful - surely there's a better way than this?

You can use a KeyboardEvent to detect numerous keys including the caps lock on most recent browsers.
The getModifierState function will provide the state for:
Alt
AltGraph
CapsLock
Control
Fn (Android)
Meta
NumLock
OS (Windows & Linux)
ScrollLock
Shift
This demo works in all major browsers including mobile (caniuse).
passwordField.addEventListener( 'keydown', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
console.log( caps ); // true when you press the keyboard CapsLock key
});

In jQuery,
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
}
});
Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.

You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)
NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.
OLD VERSION: https://jsbin.com/mahenes/edit?js,output
Also, here is a modified version (can someone test on mac and confirm)
NEW VERSION: https://jsbin.com/xiconuv/edit?js,output
NEW VERSION:
function isCapslock(e) {
const IS_MAC = /Mac/.test(navigator.platform);
const charCode = e.charCode;
const shiftKey = e.shiftKey;
if (charCode >= 97 && charCode <= 122) {
capsLock = shiftKey;
} else if (charCode >= 65 && charCode <= 90
&& !(shiftKey && IS_MAC)) {
capsLock = !shiftKey;
}
return capsLock;
}
OLD VERSION:
function isCapslock(e) {
e = (e) ? e : window.event;
var charCode = false;
if (e.which) {
charCode = e.which;
} else if (e.keyCode) {
charCode = e.keyCode;
}
var shifton = false;
if (e.shiftKey) {
shifton = e.shiftKey;
} else if (e.modifiers) {
shifton = !!(e.modifiers & 4);
}
if (charCode >= 97 && charCode <= 122 && shifton) {
return true;
}
if (charCode >= 65 && charCode <= 90 && !shifton) {
return true;
}
return false;
}
For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...
uppercase A-Z or 'Ä', 'Ö', 'Ü',
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'
The above keys are just sample representation.

You can detect caps lock using "is letter uppercase and no shift pressed" using a keypress capture on the document. But then you better be sure that no other keypress handler pops the event bubble before it gets to the handler on the document.
document.onkeypress = function ( e ) {
e = e || window.event;
var s = String.fromCharCode( e.keyCode || e.which );
if ( (s.toUpperCase() === s) !== e.shiftKey ) {
// alert('caps is on')
}
}
You could grab the event during the capturing phase in browsers that support that, but it seems somewhat pointless to as it won't work on all browsers.
I can't think of any other way of actually detecting caps lock status. The check is simple anyway and if non detectable characters were typed, well... then detecting wasn't necessary.
There was an article on 24 ways on this last year. Quite good, but lacks international character support (use toUpperCase() to get around that).

Many existing answers will check for caps lock on when shift is not pressed but will not check for it if you press shift and get lowercase, or will check for that but will not also check for caps lock being off, or will check for that but will consider non-alpha keys as 'off'. Here is an adapted jQuery solution that will show a warning if an alpha key is pressed with caps (shift or no shift), will turn off the warning if an alpha key is pressed without caps, but will not turn the warning off or on when numbers or other keys are pressed.
$("#password").keypress(function(e) {
var s = String.fromCharCode( e.which );
if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)|| //caps is on
(s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {
$("#CapsWarn").show();
} else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
(s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off
$("#CapsWarn").hide();
} //else upper and lower are both same (i.e. not alpha key - so do not hide message if already on but do not turn on if alpha keys not hit yet)
});

In JQuery. This covers the event handling in Firefox and will check for both unexpected uppercase and lowercase characters. This presupposes an <input id="password" type="password" name="whatever"/>element and a separate element with id 'capsLockWarning' that has the warning we want to show (but is hidden otherwise).
$('#password').keypress(function(e) {
e = e || window.event;
// An empty field resets the visibility.
if (this.value === '') {
$('#capsLockWarning').hide();
return;
}
// We need alphabetic characters to make a match.
var character = String.fromCharCode(e.keyCode || e.which);
if (character.toUpperCase() === character.toLowerCase()) {
return;
}
// SHIFT doesn't usually give us a lowercase character. Check for this
// and for when we get a lowercase character when SHIFT is enabled.
if ((e.shiftKey && character.toLowerCase() === character) ||
(!e.shiftKey && character.toUpperCase() === character)) {
$('#capsLockWarning').show();
} else {
$('#capsLockWarning').hide();
}
});

The top answers here didn't work for me for a couple of reasons (un-commented code with a dead link and an incomplete solution). So I spent a few hours trying everyone's out and getting the best I could: here's mine, including jQuery and non-jQuery.
jQuery
Note that jQuery normalizes the event object so some checks are missing. I've also narrowed it to all password fields (since that's the biggest reason to need it) and added a warning message. This has been tested in Chrome, Mozilla, Opera, and IE6-8. Stable and catches all capslock states EXCEPT when numbers or spaces are pressed.
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var $warn = $(this).next(".capsWarn"); // handle the warning mssg
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
$warn.show();
} else {
$warn.hide();
}
}).after("<span class='capsWarn error' style='display:none;'>Is your CAPSLOCK on?</span>");
Without jQuery
Some of the other jQuery-less solutions lacked IE fallbacks. #Zappa patched it.
document.onkeypress = function ( e ) {
e = (e) ? e : window.event;
var kc = ( e.keyCode ) ? e.keyCode : e.which; // get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed -- works for IE8-
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
alert("CAPSLOCK is on."); // do your thing here
} else {
// no CAPSLOCK to speak of
}
}
Note: Check out the solutions of #Borgar, #Joe Liversedge, and #Zappa, and the plugin developed by #Pavel Azanov, which I have not tried but is a good idea. If someone knows a way to expand the scope beyond A-Za-z, please edit away. Also, jQuery versions of this question are closed as duplicate, so that's why I'm posting both here.

We use getModifierState to check for caps lock, it's only a member of a mouse or keyboard event so we cannot use an onfocus. The most common two ways that the password field will gain focus is with a click in or a tab. We use onclick to check for a mouse click within the input, and we use onkeyup to detect a tab from the previous input field. If the password field is the only field on the page and is auto-focused then the event will not happen until the first key is released, which is ok but not ideal, you really want caps lock tool tips to display once the password field gains focus, but for most cases this solution works like a charm.
HTML
<input type="password" id="password" onclick="checkCapsLock(event)" onkeyup="checkCapsLock(event)" />
JS
function checkCapsLock(e) {
if (e.getModifierState("CapsLock")) {
console.log("Caps");
}
}
https://codepen.io/anon/pen/KxJwjq

I know this is an old topic but thought I would feed back in case it helps others. None of the answers to the question seem to work in IE8. I did however find this code that works in IE8. (Havent tested anything below IE8 yet). This can be easily modified for jQuery if required.
function capsCheck(e,obj){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('#'+obj.id).style.visibility = 'visible';
}
else document.getElementById('#'+obj.id).style.visibility = 'hidden';
}
And the function is called through the onkeypress event like this:
<input type="password" name="txtPassword" onkeypress="capsCheck(event,this);" />
<div id="capsWarningDiv" style="visibility:hidden">Caps Lock is on.</div>

This is a solution that, in addition to checking state when writing, also toggles the warning message each time the Caps Lock key is pressed (with some limitations).
It also supports non-english letters outside the A-Z range, as it checks the string character against toUpperCase() and toLowerCase() instead of checking against character range.
$(function(){
//Initialize to hide caps-lock-warning
$('.caps-lock-warning').hide();
//Sniff for Caps-Lock state
$("#password").keypress(function(e) {
var s = String.fromCharCode( e.which );
if((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)||
(s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {
this.caps = true; // Enables to do something on Caps-Lock keypress
$(this).next('.caps-lock-warning').show();
} else if((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
(s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) {
this.caps = false; // Enables to do something on Caps-Lock keypress
$(this).next('.caps-lock-warning').hide();
}//else else do nothing if not a letter we can use to differentiate
});
//Toggle warning message on Caps-Lock toggle (with some limitation)
$(document).keydown(function(e){
if(e.which==20){ // Caps-Lock keypress
var pass = document.getElementById("password");
if(typeof(pass.caps) === 'boolean'){
//State has been set to a known value by keypress
pass.caps = !pass.caps;
$(pass).next('.caps-lock-warning').toggle(pass.caps);
}
}
});
//Disable on window lost focus (because we loose track of state)
$(window).blur(function(e){
// If window is inactive, we have no control on the caps lock toggling
// so better to re-set state
var pass = document.getElementById("password");
if(typeof(pass.caps) === 'boolean'){
pass.caps = null;
$(pass).next('.caps-lock-warning').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="password" id="password" />
<span class="caps-lock-warning" title="Caps lock is on!">CAPS</span>
Note that observing caps lock toggling is only useful if we know the state of the caps lock before the Caps Lock key is pressed. The current caps lock state is kept with a caps JavaScript property on the password element. This is set the first time we have a validation of the caps lock state when the user presses a letter that can be upper or lower case. If the window loses focus, we can no longer observe caps lock toggling, so we need to reset to an unknown state.

Recently there was a similar question on hashcode.com, and I created a jQuery plugin to deal with it. It also supports the recognition of caps lock on numbers. (On the standard German keyboard layout caps lock has effect on numbers).
You can check the latest version here: jquery.capsChecker

For jQuery with twitter bootstrap
Check caps locked for the following characters:
uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';', '*', '''
lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ',', '+', '#'
/* check for CAPS LOCK on all password fields */
$("input[type='password']").keypress(function(e) {
var kc = e.which; // get keycode
var isUpperCase = ((kc >= 65 && kc <= 90) || (kc >= 33 && kc <= 34) || (kc >= 36 && kc <= 39) || (kc >= 40 && kc <= 42) || kc == 47 || (kc >= 58 && kc <= 59) || kc == 61 || kc == 63 || kc == 167 || kc == 196 || kc == 214 || kc == 220) ? true : false; // uppercase A-Z or 'Ä', 'Ö', 'Ü', '!', '"', '§', '$', '%', '&', '/', '(', ')', '=', ':', ';'
var isLowerCase = ((kc >= 97 && kc <= 122) || (kc >= 48 && kc <= 57) || kc == 35 || (kc >= 43 && kc <= 44) || kc == 46 || kc == 228 || kc == 223 || kc == 246 || kc == 252) ? true : false; // lowercase a-Z or 0-9 or 'ä', 'ö', 'ü', '.', ','
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = (e.shiftKey) ? e.shiftKey : ((kc == 16) ? true : false); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ((isUpperCase && !isShift) || (isLowerCase && isShift)) {
$(this).next('.form-control-feedback').show().parent().addClass('has-warning has-feedback').next(".capsWarn").show();
} else {
$(this).next('.form-control-feedback').hide().parent().removeClass('has-warning has-feedback').next(".capsWarn").hide();
}
}).after('<span class="glyphicon glyphicon-warning-sign form-control-feedback" style="display:none;"></span>').parent().after("<span class='capsWarn text-danger' style='display:none;'>Is your CAPSLOCK on?</span>");
live demo on jsfiddle

A variable that shows caps lock state:
let isCapsLockOn = false;
document.addEventListener( 'keydown', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
if(isCapsLockOn !== caps) isCapsLockOn = caps;
});
document.addEventListener( 'keyup', function( event ) {
var caps = event.getModifierState && event.getModifierState( 'CapsLock' );
if(isCapsLockOn !== caps) isCapsLockOn = caps;
});
works on all browsers => canIUse

This jQuery-based answer posted by #user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in #B_N 's comment: it failed detecting CapsLock while you press Shift:
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
|| ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
alert('caps is on');
}
});
Like this, it will work even while pressing Shift.

This code detects caps lock no matter the case or if the shift key is pressed:
$('#password').keypress(function(e) {
var s = String.fromCharCode( e.which );
if ( (s.toUpperCase() === s && !e.shiftKey) ||
(s.toLowerCase() === s && e.shiftKey) ) {
alert('caps is on');
}
});

I wrote a library called capsLock which does exactly what you want it to do.
Just include it on your web pages:
<script src="https://rawgit.com/aaditmshah/capsLock/master/capsLock.js"></script>
Then use it as follows:
alert(capsLock.status);
capsLock.observe(function (status) {
alert(status);
});
See the demo: http://jsfiddle.net/3EXMd/
The status is updated when you press the Caps Lock key. It only uses the Shift key hack to determine the correct status of the Caps Lock key. Initially the status is false. So beware.

Yet another version, clear and simple, handles shifted capsLock, and not constrained to ascii I think:
document.onkeypress = function (e)
{
e = e || window.event;
if (e.charCode === 0 || e.ctrlKey || document.onkeypress.punctuation.indexOf(e.charCode) >= 0)
return;
var s = String.fromCharCode(e.charCode); // or e.keyCode for compatibility, but then have to handle MORE non-character keys
var s2 = e.shiftKey ? s.toUpperCase() : s.toLowerCase();
var capsLockOn = (s2 !== s);
document.getElementById('capslockWarning').style.display = capsLockOn ? '' : 'none';
}
document.onkeypress.punctuation = [33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,91,92,93,94,95,96,123,124,125,126];
Edit: Sense of capsLockOn was reversed, doh, fixed.
Edit #2: After checking this out some more, I've made a few changes, a bit more detailed code unfortunately, but it handles more actions appropriately.
Using e.charCode instead of e.keyCode and checking for 0 values skips a lot of non-character keypresses, without coding anything specific to a given language or charset. From my understanding, it's slightly less compatible, so older, non-mainstream, or mobile browsers may not behave as this code expects, but it's worth it, for my situation anyway.
Checking against a list of known punctuation codes prevents them from being seen as false negatives, since they're not affected by caps lock. Without this, the caps lock indicator gets hidden when you type any of those punctuation characters. By specifying an excluded set, rather than an included one, it should be more compatible with extended characters. This is the ugliest, special-casiest bit, and there's some chance that non-Western languages have different enough punctuation and/or punctuation codes to be a problem, but again it's worth it IMO, at least for my situation.

React
onKeyPress(event) {
let self = this;
self.setState({
capsLock: isCapsLockOn(self, event)
});
}
onKeyUp(event) {
let self = this;
let key = event.key;
if( key === 'Shift') {
self.shift = false;
}
}
<div>
<input name={this.props.name} onKeyDown={(e)=>this.onKeyPress(e)} onKeyUp={(e)=>this.onKeyUp(e)} onChange={this.props.onChange}/>
{this.capsLockAlert()}
</div>
function isCapsLockOn(component, event) {
let key = event.key;
let keyCode = event.keyCode;
component.lastKeyPressed = key;
if( key === 'Shift') {
component.shift = true;
}
if (key === 'CapsLock') {
let newCapsLockState = !component.state.capsLock;
component.caps = newCapsLockState;
return newCapsLockState;
} else {
if ((component.lastKeyPressed !== 'Shift' && (key === key.toUpperCase() && (keyCode >= 65 && keyCode <= 90)) && !component.shift) || component.caps ) {
component.caps = true;
return true;
} else {
component.caps = false;
return false;
}
}
}

Based on answer of #joshuahedlund since it worked fine for me.
I made the code a function so it can be reused, and linked it to the body in my case. It can be linked to the password field only if you prefer.
<html>
<head>
<script language="javascript" type="text/javascript" >
function checkCapsLock(e, divId) {
if(e){
e = e;
} else {
e = window.event;
}
var s = String.fromCharCode( e.which );
if ((s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey)|| //caps is on
(s.toUpperCase() !== s && s.toLowerCase() === s && e.shiftKey)) {
$(divId).style.display='block';
} else if ((s.toLowerCase() === s && s.toUpperCase() !== s && !e.shiftKey)||
(s.toLowerCase() !== s && s.toUpperCase() === s && e.shiftKey)) { //caps is off
$(divId).style.display='none';
} //else upper and lower are both same (i.e. not alpha key - so do not hide message if already on but do not turn on if alpha keys not hit yet)
}
</script>
<style>
.errorDiv {
display: none;
font-size: 12px;
color: red;
word-wrap: break-word;
text-overflow: clip;
max-width: 200px;
font-weight: normal;
}
</style>
</head>
<body onkeypress="checkCapsLock(event, 'CapsWarn');" >
...
<input name="password" id="password" type="password" autocomplete="off">
<div id="CapsWarn" class="errorDiv">Capslock is ON !</div>
...
</body>
</html>

Mottie's and Diego Vieira's response above is what we ended up using and should be the accepted answer now. However, before I noticed it, I wrote this little javascript function that doesn't rely on character codes...
var capsLockIsOnKeyDown = {shiftWasDownDuringLastChar: false,
capsLockIsOnKeyDown: function(event) {
var eventWasShiftKeyDown = event.which === 16;
var capsLockIsOn = false;
var shifton = false;
if (event.shiftKey) {
shifton = event.shiftKey;
} else if (event.modifiers) {
shifton = !!(event.modifiers & 4);
}
if (event.target.value.length > 0 && !eventWasShiftKeyDown) {
var lastChar = event.target.value[event.target.value.length-1];
var isAlpha = /^[a-zA-Z]/.test(lastChar);
if (isAlpha) {
if (lastChar.toUpperCase() === lastChar && lastChar.toLowerCase() !== lastChar
&& !event.shiftKey && !capsLockIsOnKeyDown.shiftWasDownDuringLastChar) {
capsLockIsOn = true;
}
}
}
capsLockIsOnKeyDown.shiftWasDownDuringLastChar = shifton;
return capsLockIsOn;
}
}
Then call it in an event handler like so capsLockIsOnKeyDown.capsLockIsOnKeyDown(event)
But again, we ended up just using #Mottie s and #Diego Vieira s response

How about using getModifierState()
The getModifierState() method returns true if the specified modifier
key was pressed, or activated.
You can use it like:
function checkIfCapsLockIsOn(event) {
var capsLockIsOn = event.getModifierState("CapsLock");
console.log("Caps Lock activated: " + capsLockIsOn);
}
This will simply check if CapsLock is ON or OFF and show it in console. You can change the way the function you want to work.
And then use this function on keydown or keyup for example.
<input type="text" onkeydown="checkIfCapsLockIsOn(event)">

In this below code it will be show alert when Caps lock on and they press key using shift.
if we return false; then current char will not append to text page.
$('#password').keypress(function(e) {
// e.keyCode is not work in FF, SO, it will
// automatically get the value of e.which.
var s = String.fromCharCode( e.keyCode || e.which );
if ( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey ) {
alert('caps is on');
return false;
}
else if ( s.toUpperCase() !== s) {
alert('caps is on and Shiftkey pressed');
return false;
}
});

try this out simple code in easy to understand
This is the Script
<script language="Javascript">
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
document.getElementById('divMayus').style.visibility = 'visible';
else
document.getElementById('divMayus').style.visibility = 'hidden';
}
</script>
And the Html
<input type="password" name="txtPassword" onkeypress="capLock(event)" />
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>

try to use this code.
$('selectorOnTheInputTextBox').keypress(function (e) {
var charCode = e.target.value.charCodeAt(e.target.value.length - 1)
var capsOn =
e.keyCode &&
!e.shiftKey &&
!e.ctrlKey &&
charCode >= 65 &&
charCode <= 90;
if (capsOn)
//action if true
else
//action if false
});
Good Luck :)

Here is a custom jquery plugin, using jquery ui, made up of all the good ideas on this page and leverages the tooltip widget. The caps lock message is auto applied all password boxes and requires no changes to your current html.
Custom plug in code...
(function ($) {
$.fn.capsLockAlert = function () {
return this.each(function () {
var capsLockOn = false;
var t = $(this);
var updateStatus = function () {
if (capsLockOn) {
t.tooltip('open');
} else {
t.tooltip('close');
}
}
t.tooltip({
items: "input",
position: { my: "left top", at: "left bottom+10" },
open: function (event, ui) {
ui.tooltip.css({ "min-width": "100px", "white-space": "nowrap" }).addClass('ui-state-error');
if (!capsLockOn) t.tooltip('close');
},
content: function () {
return $('<p style="white-space: nowrap;"/>')
.append($('<span class="ui-icon ui-icon-alert" style="display: inline-block; margin-right: 5px; vertical-align: text-top;" />'))
.append('Caps Lock On');
}
})
.off("mouseover mouseout")
.keydown(function (e) {
if (e.keyCode !== 20) return;
capsLockOn = !capsLockOn;
updateStatus();
})
.keypress(function (e) {
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
if (!isUp && !isLow) return; //This isn't a character effected by caps lock
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = (e.shiftKey) ? e.shiftKey : ((kc === 16) ? true : false); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ((isUp && !isShift) || (isLow && isShift)) {
capsLockOn = true;
} else {
capsLockOn = false;
}
updateStatus();
});
});
};
})(jQuery);
Apply to all password elements...
$(function () {
$(":password").capsLockAlert();
});

Javascript Code
<script type="text/javascript">
function isCapLockOn(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
document.getElementById('alert').style.visibility = 'visible';
else
document.getElementById('alert').style.visibility = 'hidden';
}
</script>
We now need to associate this script using Html
<input type="password" name="txtPassword" onkeypress="isCapLockOn(event)" />
<div id="alert" style="visibility:hidden">Caps Lock is on.</div>

it is late i know but, this can be helpfull someone else.
so here is my simpliest solution (with Turkish chars);
function (s,e)
{
var key = e.htmlEvent.key;
var upperCases = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZXWQ';
var lowerCases = 'abcçdefgğhıijklmnoöprsştuüvyzxwq';
var digits = '0123456789';
if (upperCases.includes(key))
{
document.getElementById('spanLetterCase').innerText = '[A]';
}
else if (lowerCases.includes(key))
{
document.getElementById('spanLetterCase').innerText = '[a]';
}
else if (digits.includes(key))
{
document.getElementById('spanLetterCase').innerText = '[1]';
}
else
{
document.getElementById('spanLetterCase').innerText = '';
}
}

So I found this page and didn't really like the solutions I found so I figured one out and am offering it up to all of you. For me, it only matters if the caps lock is on if I'm typing letters. This code solved the problem for me. Its quick and easy and gives you a capsIsOn variable to reference whenever you need it.
let capsIsOn=false;
let capsChecked=false;
let capsCheck=(e)=>{
let letter=e.key;
if(letter.length===1 && letter.match(/[A-Za-z]/)){
if(letter!==letter.toLowerCase()){
capsIsOn=true;
console.log('caps is on');
}else{
console.log('caps is off');
}
capsChecked=true;
window.removeEventListener("keyup",capsCheck);
}else{
console.log("not a letter, not capsCheck was performed");
}
}
window.addEventListener("keyup",capsCheck);
window.addEventListener("keyup",(e)=>{
if(capsChecked && e.keyCode===20){
capsIsOn=!capsIsOn;
}
});

When you type, if caplock is on, it could automatically convert the current char to lowercase. That way even if caplocks is on, it will not behave like it is on the current page. To inform your users you could display a text saying that caplocks is on, but that the form entries are converted.

There is a much simpler solution for detecting caps-lock:
function isCapsLockOn(event) {
var s = String.fromCharCode(event.which);
if (s.toUpperCase() === s && s.toLowerCase() !== s && !event.shiftKey) {
return true;
}
}

Related

How do i restrict some specific special character from input? [duplicate]

How do I block special characters from being typed into an input field with jquery?
A simple example using a regular expression which you could change to allow/disallow whatever you like.
$('input').on('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Short answer: prevent the 'keypress' event:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
Long answer: Use a plugin like jquery.alphanum
There are several things to consider when picking a solution:
Pasted text
Control characters like backspace or F5 may be prevented by the above code.
é, í, ä etc
Arabic or Chinese...
Cross Browser compatibility
I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:
$("input").alphanum();
Or for more fine-grained control, add some settings:
$("#username").alphanum({
allow : "€$£",
disallow : "xyz",
allowUpper : false
});
Hope it helps.
Use simple onkeypress event inline.
<input type="text" name="count" onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">
Use HTML5's pattern input attribute!
<input type="text" pattern="^[a-zA-Z0-9]+$" />
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $#()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});
Your textbox:
<input type="text" id="name">
Your javascript:
$("#name").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
this is an example that prevent the user from typing the character "a"
$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
return false;
});
});
key codes refrence here:
http://www.expandinghead.net/keycode.html
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});
Write some javascript code on onkeypress event of textbox.
as per requirement allow and restrict character in your textbox
function isNumberKeyWithStar(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
return false;
return true;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isNumberKeyForAmount(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
To replace special characters, space and convert to lower case
$(document).ready(function (){
$(document).on("keyup", "#Id", function () {
$("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
});
});
Yes you can do by using jQuery as:
<script>
$(document).ready(function()
{
$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='empty') // if username is empty
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='invalid') // if special characters used in username
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='no') // if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>
and script for your user_availability.php will be:
<?php
include'includes/config.php';
//value got from the get method
$user_name = trim($_POST['user_name']);
if($user_name == ''){
echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $user_name)){
echo "invalid";
}else{
$select = mysql_query("SELECT user_id FROM staff");
$i=0;
//this varible contains the array of existing users
while($fetch = mysql_fetch_array($select)){
$existing_users[$i] = $fetch['user_id'];
$i++;
}
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not availble
echo "no";
}
else
{
//user name is available
echo "yes";
}
}
?>
I tried to add for / and \ but not succeeded.
You can also do it by using javascript & code will be:
<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode;
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="#" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
return false;
} else {
return true;
}
}
</script>
<!-- Check special characters in username end -->
<!-- in your form -->
User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>
just the numbers:
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=57) {
return true; } else {
return false; } });
or for time including ":"
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=58) {
return true; } else {
return false; } });
also including delete and backspace:
$('input.time').keydown(function(e) { if((e.keyCode>=46 &&
e.keyCode<=58) || e.keyCode==8) { return true; } else {
return false; } });
unfortuneatly not getting it to work on a iMAC
Wanted to comment on Alex's comment to Dale's answer. Not possible (first need how much "rep"? That wont happen very soon.. strange system.)
So as an answer:
Backspace can be added by adding \b to the regex definition like this: [a-zA-Z0-9\b].
Or you simply allow the whole Latin range, including more or less anything "non exotic" characters (also control chars like backspace): ^[\u0000-\u024F\u20AC]+$
Only real unicode char outside latin there is the euro sign (20ac), add whatever you may need else.
To also handle input entered via copy&paste, simply also bind to the "change" event and check the input there too - deleting it or striping it / giving an error message like "not supported characters"..
if (!regex.test($j(this).val())) {
alert('your input contained not supported characters');
$j(this).val('');
return false;
}
Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
some_element.bind("keypress", function(event) {
// prevent if in array
if($.inArray(event.which,specialChars) != -1) {
event.preventDefault();
}
});
In Angular, I needed a proper currency format in my textfield. My solution:
var angularApp = angular.module('Application', []);
...
// new angular directive
angularApp.directive('onlyNum', function() {
return function( scope, element, attrs) {
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
// prevent these special characters
element.bind("keypress", function(event) {
if($.inArray(event.which,specialChars) != -1) {
prevent( scope, event, attrs)
}
});
var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
,57,96,97,98,99,100,101,102,103,104,105,110,190];
element.bind("keydown", function(event) {
if($.inArray(event.which,allowableKeys) == -1) {
prevent( scope, event, attrs)
}
});
};
})
// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
In the html add the directive
<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">
and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'
...
this.updateRequest = function() {
amount = $scope.amount;
if (amount != undefined) {
document.getElementById('spcf').onkeypress = function (e) {
// only allow one period in currency
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
// Remove "." When Last Character and round the number on blur
$("#amount").on("blur", function() {
if (this.value.charAt(this.value.length-1) == ".") {
this.value.replace(".","");
$("#amount").val(this.value);
}
var num = parseFloat(this.value);
// check for 'NaN' if its safe continue
if (!isNaN(num)) {
var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
$("#amount").val(num);
}
});
this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}
...
You don't need jQuery for this action
You can achieve this using plain JavaScript, You can put this in the onKeyUp event.
Restrict - Special Characters
e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()
Accept - Number only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
Accept - Small Alphabet only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
I could write for some more scenarios but I have to maintain the specific answer.
Note It will work with jquery, react, angular, and so on.
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if( $(this).val().indexOf('.') == 0){
$(this).val("");
}
//this is the simplest way
indexof is used to validate if the input started with "."
[User below code to restrict special character also
$(h.txtAmount).keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});]
Allow only numbers in TextBox (Restrict Alphabets and Special Characters)
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
/**
* Forbids special characters and decimals
* Allows numbers only
* */
const numbersOnly = (evt) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
let inputResult = /^[0-9]*$/.test(evt.target.value);
if (!inputResult) {
evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
}
return true;
}
In HTML:
<input type="text" (keypress)="omitSpecialChar($event)"/>
In JS:
omitSpecialChar(event) {
const keyPressed = String.fromCharCode(event.keyCode);
const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
return verifyKeyPressed === true;
}
In this example it is possible to type accents.
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
$('#Description').on('change', function() {
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}
A more enhanced form would be
$('input[type=text]').on('input', function() {
var c = this.selectionStart,
r = /[^a-z ]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Because it will allow you to enter space as well and it will only target the input fields with type text and wont bother the other input fields like email, password etc as normally we need special characters in email and password field

Detecting when CAPS LOCK is ON

I have this code for adding a keypress to a password. If capslock is on it will trigger. I got it from How do you tell if caps lock is on using JavaScript?
$("input[type='password']").keypress(function(e) {
var $warn = $(this).next(".capsWarn"); // handle the warning mssg
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
$warn.show();
} else {
$warn.hide();
}
}).after(capLock());
function capLock(e){
alert('CAPSLOCK is ON');
}
The original code has the message in a span:
...}).after(<span class='capsWarn error' style='display:none;'>CAPSLOCK is ON</span>);
I wanted it to be an alert message but it is not performing as I expect it to. On load it should alert the message but even if the capslock is on it is not showing the alert.
How do I get it to detect the key and present the alert?
$("input[type='password']").keypress(function(e) {
var $warn = $(this).next(".capsWarn");//can be removed since you are just using alert
var kc = e.which; //get keycode
var isUp = (kc >= 65 && kc <= 90) ? true : false; // uppercase
var isLow = (kc >= 97 && kc <= 122) ? true : false; // lowercase
// event.shiftKey does not seem to be normalized by jQuery(?) for IE8-
var isShift = ( e.shiftKey ) ? e.shiftKey : ( (kc == 16) ? true : false ); // shift is pressed
// uppercase w/out shift or lowercase with shift == caps lock
if ( (isUp && !isShift) || (isLow && isShift) ) {
capLock(); // alerts "CAPSLOCK is ON"
}
});
function capLock() {
alert('CAPSLOCK is ON');
}

Restriciting enterting of alphabets in jquery mobile

I am using a text box with type number. For xperia mobile's if i am using the same text box,it is showing a keyboard with all the value.So i am able to type any value. I want to restrict the user from entering any value.User have to enter only number.I tried the following code.
*
document.getElementById('loginPin').addEventListener('keyup', function(e){
var keyCode = ('which' in e) ? e.which : e.keyCode;
var isNumeric = (keyCode < 48 KeyboardEvent.DOM_VK_0 && keyCode > 57 KeyboardEvent.DOM_VK_9 ) ||
(keyCode < 96 KeyboardEvent.DOM_VK_NUMPAD0 && keyCode > 105 KeyboardEvent.DOM_VK_NUMPAD9 );
var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
var V = $(this).val();
alert("hai"+V);
if (isNaN(V)) {
$(this).val(V.replace(/[^0-9]/g,''));
}
}, false);
*
It is working if the alert is there, else it is not working. So any suggestion to solve this.
function numericInput(inputId){
$('#' + inputId).keyup(function (e) {
var regex = new RegExp("^[0-9]+$");
if (!regex.test($(this).val())) {
$(this).val($(this).val().slice(0, -1));
e.preventDefault();
return false;
}
});
}

HTML5 restricting input characters

Is it possible to restrict the input of certain characters in HTML5/JavaScript? For example, could I have an input textbox on the screen and if the user tries to type a letter in it, it wouldn't show up in the box because I've restricted it to only numbers?
I know you can use a pattern which will be checked on submit, but I want the "bad" characters to just never be entered at all.
The input textbox
<input type="text" onKeyDown="myFunction()" value="" />
JavaScript
function myFunction() {
var e = event || window.event; // get event object
var key = e.keyCode || e.which; // get key cross-browser
if (key < 48 || key > 57) { //if it is not a number ascii code
//Prevent default action, which is inserting character
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
}
Use html5 pattern attribute for inputs:
<input type="text" pattern="\d*" title="Only digits" />
OR
Use html5 number type for input :
<input type="number" />
To slightly improve off of jonhopkins excellent answer, I added backspace and delete key acceptance like so:
function inputValidate(){
var e = event || window.event;
var key = e.keyCode || e.which;
if (((key>=48)&&(key<=57))||(key==8)||(key == 46)) { //allow backspace //and delete
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
}
}
For Restricting Characters symbols like '-' and ','
<input type="text" pattern="[^-,]+">
for restricting numbers
<input type="text" pattern="[^0-9]+">
for restricting letters of the alphabet
<input type="text" pattern="[^a-zA-Z]+">
KeyboardEvent.keyCode is deprecated, so here's a solution using the HMLElement.input event. This solution uses a simple regex, and handles copy-paste nicely as well by just removing the offending elements from any input.
My regex: /[^\w\d]/gi
Matches anything not (^) a word character (\w: a-z) or a digit (\d: 0-9).
g modifier makes regex global (don't return after first match)
i modifier makes regex case insensitive
With this regex, special characters and spaces won't be allowed. If you wanted to add more, you'd just have to add allowed characters to the regex list.
function filterField(e) {
let t = e.target;
let badValues = /[^\w\d]/gi;
t.value = t.value.replace(badValues, '');
}
let inputElement = document.getElementById('myInput');
inputElement.addEventListener('input', filterField);
<input id="myInput" type="text" style="width: 90%; padding: .5rem;" placeholder="Type or paste (almost) anything...">
//improved wbt11a function
function numberFieldStrictInput(allowcomma, allownegative) {
var e = event || window.event; // get event object
var key = e.keyCode ||`enter code here` e.which; // get key cross-browser
if(key==8 || key==46 || key == 9 || key==17 || key==91 || key==18 ||
key==116 || key==89 || key==67 || key==88 || key==35 || key==36) //back, delete tab, ctrl, win, alt, f5, paste, copy, cut, home, end
return true;
if(key == 109 && allownegative)
return true;
if(key == 190 && allowcomma)
return true;
if(key>=37 && key<=40) //arrows
return true;
if(key>=48 && key<=57) // top key
return true;
if(key>=96 && key<=105) //num key
return true;
console.log('Not allowed key pressed '+key);
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
//on input put onKeyDown="numberFieldStrictInput(1,0)"
What about this (it supports special keys, like copy, paste, F5 automatically)?
function filterNumericInput() {
var e = event || window.event; // get event object
if (e.defaultPrevented) {
return;
}
const key = e.key || e.code;
if ((e.key.length <= 1) && (!(e.metaKey || e.ctrlKey || e.altKey))) {
if (!((key >= '0' && key <= '9') || (key === '.') || (key === ',') || (key === '-') || (key === ' '))) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}
Limit input to letters, numbers and '.' (for React users only)
Here is my simple solution, I couldn't find a better solution for React and made my own. 3 steps.
First, create a state.
const [tagInputVal, setTagInputVal] = useState("");
Then, use the state as input value (value={tagInputVal}) and pass the event to the onChange handler.
<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>
Then, set the value of the event inside onChange handler.
function onChangeTagInput(e) {
setTagInputVal(e.target.value.replace(/[^a-zA-Z\d.]/ig, ""));
}
var keybNumberAndAlpha = new keybEdit(' 0123456789abcdefghijklmnopqrstuvwxyz');
function keybEdit(strValid, strMsg) {
var reWork = new RegExp('[a-z]','gi'); // Regular expression\
// Properties
if(reWork.test(strValid))
this.valid = strValid.toLowerCase() + strValid.toUpperCase();
else
this.valid = strValid;
if((strMsg == null) || (typeof(strMsg) == 'undefined'))
this.message = '';
else
this.message = strMsg;
// Methods
this.getValid = keybEditGetValid;
this.getMessage = keybEditGetMessage;
function keybEditGetValid() {
return this.valid.toString();
}
function keybEditGetMessage() {
return this.message;
}
}
function editKeyBoard(ev, objForm, objKeyb) {
strWork = objKeyb.getValid();
strMsg = ''; // Error message
blnValidChar = false; // Valid character flag
var BACKSPACE = 8;
var DELETE = 46;
var TAB = 9;
var LEFT = 37 ;
var UP = 38 ;
var RIGHT = 39 ;
var DOWN = 40 ;
var END = 35 ;
var HOME = 35 ;
// Checking backspace and delete
if(ev.keyCode == BACKSPACE || ev.keyCode == DELETE || ev.keyCode == TAB
|| ev.keyCode == LEFT || ev.keyCode == UP || ev.keyCode == RIGHT || ev.keyCode == DOWN) {
blnValidChar = true;
}
if(!blnValidChar) // Part 1: Validate input
for(i=0;i < strWork.length;i++)
if(ev.which == strWork.charCodeAt(i) ) {
blnValidChar = true;
break;
}
// Part 2: Build error message
if(!blnValidChar)
{
//if(objKeyb.getMessage().toString().length != 0)
// alert('Error: ' + objKeyb.getMessage());
ev.returnValue = false; // Clear invalid character
ev.preventDefault();
objForm.focus(); // Set focus
}
}
<input type="text"name="worklistFrmDateFltr" onkeypress="editKeyBoard(event, this, keybNumberAndAlpha)" value="">
I found that onKeyDown captures Shift key, arrows, etc. To avoid having to account for this, I could filter out character input easily by subscribing to onKeyPress instead.
Since many of the answers above didn't satisfy me, I propose my solution which solves the problem of the input event being uncancelable by storing the previous value in a custom attribute, and restoring it in case the pattern is not matched:
const input = document.querySelector('#input-with-pattern')
input.addEventListener('keyup', event => {
const value = event.target.value;
if (!/^[a-zA-Z]+$/.test(value) && value !== '') { // it will allow only alphabetic
event.target.value = event.target.getAttribute('data-value');
} else {
event.target.setAttribute('data-value', value);
}
});
<input id="input-with-pattern">

event key code for ampersand?

I am trying to find the keycode for ampersand and underscore. I should not allow my users to allow to enter ampersands and underscores. I was taking a look at one list, and it mentions 55 as the keycode for both 7 & ampersand, and another list says that 55 is the keycode for 7. So if I return false when my user hits the keycode 55, I am disallowing the user from using 7, which isn't the requirement. How do I find the keycodes for ampersand and underscore?
I just tried with 55, but it only is giving me the alert for 7 not with ampersand!
function noenter(e)
{
evt = e || window.event;
var keyPressed = evt.which || evt.keyCode;
if(keyPressed==13)
{
return false;
}
else if(evt.shiftKey && keyPressed===55)
// else if(keyPressed==59 || keyPressed==38 || keyPressed==58 || keyPressed==95)
{
alert("no special characters");
return false;
}
}
Use the keypress event and test directly for the character as follows. Don't mess with key codes: they will vary between different keyboard types and cultures. Character codes won't.
var el = document.getElementById("your_input");
el.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
if (charStr == "&" || charStr == "_") {
alert(charStr);
return false;
}
};
Check if the shift key is down:
//e = Event
(e.shiftKey && e.keyCode === 55) //returns true if Shift-7 is pressed
ok got it! it is 38! sorry for putting up this question!
I've solved it using the Unicode Key Identifier. Below is my implementation with jQuery:
function parseKey(key) {
return parseInt(key.substring(2), 10);
}
$inputs.bind('keydown', function(e) {
var c=parseKey(e.originalEvent.keyIdentifier);
//allow only numbers and backspace
if ((c<30 || c>39) && e.which!=8)
e.preventDefault();
if (e.which == 13)
$(this).blur();
});

Categories

Resources