At the moment, I have an input. I am allowed to enter any characters, even special characters, no digits.
What I've tried so far is to setup a keydown and a keyup event.
ng-keydown="vm.preventNumberInput($event)"
ng-onkeyup="vm.preventNumberInput($event)"
vm.preventNumberInput = function (e) {
var keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode > 47 && keyCode < 58 || keyCode > 95 && keyCode < 107) {
e.preventDefault();
}
}
This works okay, but it prevents me from adding special characters like !##%^&*.
May I ask how do I allow characters from being entered into my input that aren't digits.
Check the event's key property to get the pressed key. If it matches \d (a digit), call preventDefault:
vm.preventNumberInput = function (e) {
if (/\d/.test(e.key)) {
e.preventDefault();
}
}
Any characters other than digits will be allowed.
(note that the keyCode and which properties are deprecated, and should be avoided when possible)
Related
i tried pattern pattern="[A-Za-z]" attribute of input type but it allows first and show error at last on form submit
any example of js,jq will be much helpful and appreciated
Thanks..
The Expression you provided must be modified to: ^[A-Za-z -]+$
You can use either from below to match you criteria :
0 or more of the preceding expression
1 or more of the preceding expression
You can also onchange or onblur add method As ValidateText ex :
function lettersOnly()
{
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)
return true;
else
return false;
}
link : Javascript Function to enter only alphabets on keypress
I am trying to create a directive that only accepts characters input in textbox which is A-Z and a-z. This is my directive:
angApp.directive('onlyCharacters', function () {
return {
link: function (scope, elem, attrs) {
$(elem).keydown(function (e) {
if (!((e.keyCode >= 65 && e.keyCode <= 90) ||
e.keyCode == 8 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 9)
) {
e.preventDefault();
}
});
}
}
});
This even works for small a-z. I am wondering how does that. Isn't ascii keys for lowercase A-Z is 97-122? However the above directive works for upper as well as lower case.
Please suggest how does the above code work for lower case?
The short answer is that keyup and keydown are used to identify the physical keys pressed not the value which those keys correspond to. Compare the codes to the ones you get from the keypress event.
You'll see that you are correct with regard to the key ranges in keypress but both a and A are achieved by hitting the same physical key => same key code in keyup and keydown.
I have an input field which I only want positive and negative integers to be allowed in. I track their typing with onkeyup() since that's the most consistent across browsers. The real issue comes in when trying to replace non-numeric characters without replacing the dash at the start.
if(e.keyCode < 48 || e.keyCode > 57) {
var data = e.target.value;
if(e.target.value.match(/^[-]?/))
e.target.value = '-' + data.substr(1).replace(/\D*/, "");
else
e.target.value = data.replace(/\D*/,"");
}
Basically what's happening here is I ignore when they type in numbers, but for everything else attempt to replace anything they may have added that isn't a number. The issue with this right now is when I press Backspace, the dash comes back right away for some reason.
E.g. My input field has this: - When I press backspace. My input field stays as this: -
WORKING CODE:
if(e.keyCode < 48 || e.keyCode > 57) {
var data = e.target.value;
if(e.target.value.match(/^[-]+/))
e.target.value = '-' + data.substr(1).replace(/\D/, "");
else { console.log('else');
e.target.value = data.replace(/\D/,"");
}
}
Change
if(e.keyCode < 48 || e.keyCode > 57) {
to
if((e.keyCode < 48 || e.keyCode > 57) && e.keyCode!=8) {
Then you'll ignore the backspace character just like a number, which won't cause any other issues.
I just figured out the issue, Renegade has a decent method, but I made a Regex mistake. It should be this:
if(e.target.value.match(/^[-]+/))
Rather than:
if(e.target.value.match(/^[-]?/))
Since the latter will give true even if the dash does not exist. ? means 0 or 1 matches, + is 1 or more.
I wrote the following code (using jQuery) to show the pressed key.
$(window).keydown(function(e){
$("div").text("Key:" + String.fromCharCode(e.keyCode).toLowerCase());
return false;
});
This code works in normal alphabet characters (q,w,e,r...).
But when I press non alphabet keys (like ']'), an incorrect character is shown.
ex: ',' -> ¼, ']' -> ý
What's wrong with my code?
Use the keypress event and e.which property.
jQuery normalizes the keycodes, and stores the variable in event.which. The keypress event's which property is the only reliable value for String.fromCharCode.
The event.keyCode property may not be equal to the event.charCode or event.which properties.
For non-printable characters, event.which has a value of zero, contrary to event.keyCode. That's why you're seeing weird characters.
$(window).keypress(function(e) {
var charCode = e.which;
if (!charCode) { // <-- charCode === 0
return;// return false, optionally
}
$("div").text("Key:" + String.fromCharCode(charCode).toLowerCase());
return false; // Or e.preventDefault(); and/or e.stopPropagation()
}).keyup(function(e) {
// Key is lifted, do something
});
Greetings all. I have the following function to validate input depending if is numeric, alpha, alphanumeric and email:
function permite(e, permitidos) {
var key = e.keyCode || e.which;
//Validate if its an arrow or delete button
if((key == 46) || (key == 8) || (key >= 37 && key <= 40))
return true;
var keychar = String.fromCharCode(key);
switch(permitidos) {
case 'num':
permitidos = /^[0-9]$/;
break;
case 'car':
permitidos = /^[\sa-zA-Z]$/;
break;
case 'num_car':
permitidos = /^[\sa-zA-Z0-9]$/;
break;
case 'correo':
permitidos = /^[a-zA-Z0-9._\-+#]$/;
break;
}
return permitidos.test(keychar);
}
The var names are in spanish but its an easy function to understand.
The problem is the following. The keycode for '%' is 37 the same than the left arrow and the keycode for '(' is 40 the same than the right arrow. So my function is not validating '%' and '(' and it sucks. I dont know what to do, please help.
The keypress event doesn't fire for arrow and delete keys, so you can just remove your if statement. Darn you FireFox!
You are mixing up keyCode and charCode, which is understandable because event.keyCode actually contains charCode for keyPress events, unlike keydown and keyup. The keyCode for ( is 57 (same as for 9 - those characters are on the same key). Its charCode is 40. Arrow keys don't have charCodes, so they don't fire keypress events. (Except in FireFox... Argh!)
Your best bet is to use the keydown event and look for keyCode rather than charCode, checking for shift keys when necessary. You'll have to manually map keyCodes to characters when the shift key is pressed.
Slightly OT (apologies) but you may want to look at one of the Javascript libraries out there, for example JQuery; almost all of them come with (or have) libraries for "validating input".
For example: if you were using JQuery you may consider the "Validation" plugin - http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Check for whether the shift key is being pressed as well by checking event.shiftKey:
//Validate if its an arrow or delete button
if((key == 46) || (key == 8) || (key >= 37 && key <= 40 && !e.shiftKey))
return true;
Another option (depending on your application) is to handle the keydown event instead of the keypress event, which won't result in overlapping key codes.