I have the following validation to allow only numbers and a decimal in Javascript
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
I call this in my textbox element like onkeypress='validate(event)'
This code works fine in IE but when I try the same with Firefox backspace, left and right arrow keys and space does not work.
How would I fix this?
Using key press is the right solution, but you simply need to attach the event handler by JS (which is considered better practice anyway), and use something like this:
$('#myInput').keypress(function(event){
validate(event)
});
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if (key <48 || key > 57 || key == 190)//keycode is a number between 0 and 9 or '.'
...
};
use keyup or keydown instead of keypress
keypress is only supposed to fire when there is a character insert
http://www.quirksmode.org/dom/events/keys.html
keydown function would work across all browsers. Please use keydown function and it would work!
Ex.:-
$(document).keydown(function (e){
if(e.keyCode == 37) // left arrow
{
//code for left arrow
}
else if(e.keyCode == 39) // right arrow
{
//code for right arrow
}
});
Try
//allows number and hyphen only
function isNumeric(e)
{
var a = e.charCode;
if(a==0){return;}
return ((a >= 48 && a <= 57));
}
</script>
Firefox Backspace charcode 0.
Related
I have run the normal textbox in android device an i have face some issues which is mentioned below.
1.Keypress event does not triggered in android device
2.keycode value always return as 229 only
How to resolve this issue?
Normal keypress event does not give keyCode in android device. There has already been a big discussion on this.
If you want to capture the press of space bar or special chars, you can use keyup event.
$('#input').on('keyup', e => {
var keyCode = e.keyCode || e.which;
if (keyCode == 0 || keyCode == 229) {
keyCode = e.target.value.charAt(e.target.selectionStart - 1).charCodeAt();
}
})
just check your input characters keyCode, if it is 0 or 229 then here is the function getKeyCode which uses charCodeAt of JS to return the KeyCode which takes input string a parameter and returns keycode of last character.
<script>
var getKeyCode = function (str) {
return str.charCodeAt(str.length);
}
$('#myTextfield').on('keyup',function(e){
//for android chrome keycode fix
if (navigator.userAgent.match(/Android/i)) {
var inputValue = this.value;
var charKeyCode = e.keyCode || e.which;
if (charKeyCode == 0 || charKeyCode == 229) {
charKeyCode = getKeyCode(inputValue);
alert(charKeyCode+' key Pressed');
}else{
alert(charKeyCode+' key Pressed');
}
}
});
</script>
I have been using jquery to capture the keydown event and validate the entered text for different cases like: characters only, alpha-numeric, characters and spaces etc.
Regex used:
Characters with spaces: ^[a-zA-Z ]+$
Characters only: ^[a-zA-Z]+$
Alphanumerics: ^[a-zA-Z0-9]+$
This is how I am using the bind function:
$('.chars_and_space_only').bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z ]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
All of above uses cases are working fine, however I have to now include characters, spaces, apostrophe and periods. So this is the method I have modified:
$(".chars_space_dots_apostrophes_only").bind('keydown', function (event) {
// http://stackoverflow.com/a/8833854/260665
var eventCode = !event.charCode ? event.which : event.charCode;
if((eventCode >= 37 && eventCode <= 40) || eventCode == 8 || eventCode == 9 || eventCode == 46) { // Left / Right Arrow, Backspace, Delete keys
return;
}
// http://stackoverflow.com/a/8833854/260665
var regex = new RegExp("^[a-zA-Z '.]+$");
var key = String.fromCharCode(eventCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
This, strangely doesn't seem to work. Here is the fiddle: https://jsfiddle.net/ugu8f4y3/
Regex used: ^[a-zA-Z '.]+$
Regex validator does validate this text for the above regex:
Hello. World's
But the text field in fiddle does not allow me to enter periods and apostrophes, is there something I am missing here?
The problem is with jquery and the keydown event. Replace it with keypress and you'll be good to go. You should also only need to check in which.
keydown and keyup are important for cases when you're concerned with the position of the key's physical location. In this case you want to know that the key was depressed and handle the resulting input. jquery will normalize the character codes differently.
Further information about the differences between keypress, keydown and key up.
Updated Fiddle
I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
#Html.TextBoxFor(model => model.ProductName, new { #class = "form-
control", #onkeypress = "return OnlyAlphaNumeric(this);", #onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
Your problem has nothing related to regular expressions.
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
Demo
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
Demo
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
You can try this, it may solve your problem.
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}
I have an HTML form in which I need to allow only numeric key-press. For this i have used the following code
$(".span8").keypress(function(e)
{
var unicode=e.charCode? e.charCode : e.keyCode
//alert(unicode);
if ((unicode ==8) || (unicode==9)|| (unicode==46)){
//if the key isn't the backspace key (which we should allow)
}
else
{
if (unicode<48||unicode>57&&unicode!=65) //if not a number
return false //disable key press
}
});
but here if I am testing keycode, I am getting value as 46 for delete key. 46 is for dot(- period)
Others values are coming correct. I am not able to find were am I going wrong.
Please help
I've found this weird behaviour too with the keypress function.
Instead, try the following:
jQuery(function($) {
var input = $('.span8');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if(key == 8 || key == 46)
//Do something when DEL or Backspace is pressed
});
});
I'm trying to build a communal wall, that appears the same for all those who access the web page, and syncs between users. I'm struggling to capture keyboard input correctly to apply to the canvas. My function is based on document.onkeydown, and can be seen in the 'script.js' referenced in the said web page. It can be seen working when you double click a word and the write.
Unfortunately this seems to be failing to capture anything but capital letters, and I'm looking for an alternate way to go about this. I've looked into the 'textInput' event, described in this page, however it seems to be only supported by WebKit browsers, and I want to build something which works generically. Can someone suggest an alternate way to go about capturing keyboard input for use in canvas? Or perhaps I'm doing something silly?
Code described is here:
document.onkeydown = keyHandler;
function keyHandler(e)
{
var pressedKey;
if (document.all) { e = window.event;
pressedKey = e.keyCode; }
if (e.which) {
pressedKey = e.which;
}
if (pressedKey == 8) {
e.cancelBubble = true; // cancel goto history[-1] in chrome
e.returnValue = false;
}
if (pressedKey == 27)
{
// escape key was pressed
keyCaptureEdit = null;
}
if (pressedKey != null && keyCaptureEdit != null)
{
keyCaptureEdit.callback(pressedKey);
}
}
... Later on in code describing each text object ...
keyCaptureEdit.callback = function (keyCode) {
var keyCaptured = String.fromCharCode(keyCode);
if (keyCaptured == "\b" ) { //backspace character
t.attrs.timestamp = t.attrs.timestamp + 1;
t.setText(t.getText().slice(0, -1));
}
else if (keyCode == 32 || keyCode >= 48 && keyCode <= 57 || keyCode >= 65 && keyCode <= 90)
{
t.attrs.timestamp = t.attrs.timestamp + 1;
t.setText(t.getText() + keyCaptured);
}
layer.draw();
}
Well one trivial way to change your code would be to keep track of the shift key:
...
{
keyCaptureEdit.callback(pressedKey, e.shiftKey); // <-- keep track of shift key
}
}
...
keyCaptureEdit.callback = function (keyCode, shift) {
var keyCaptured = String.fromCharCode(keyCode);
// shift key not pressed? Then it's lowercase
if (shift === false) keyCaptured = keyCaptured.toLowerCase()
But that doesn't account for CapsLock.
In jQuery its really simple because the right key code is done for you:
$(document).keypress(function(event) {
var keyCaptured = String.fromCharCode(event.keyCode);
console.log(keyCaptured);
});
In that example the console will correctly log P or p depending on what would be typed.