I am using a onKeyDown and a regular expression to parse keyboard input. I need it to all A-Z, backspace, and question mark. The problem comes with the ?, I cannot get it to be accepted. I have tried
/[A-Z\x08?]/
/[A-Z\x08\?]/
/[A-Z\x08\\?]/
/[A-Z\x08\x3F]/
None of which allow the ? to be accepted.
function kd(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[A-Z\x08]/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Any help would be greatly appreciated.
The question mark should go inside the character class:
/[A-Z\x08?]/
Another problem is that you should be using onkeypress to determine which character was typed. The onkeyup and onkeydown events only tell you which keys were pressed and released, but they don't say what characters these correspond to. On different keyboards you have to press different keys to generate the same character.
For example on my keyboard I have to press Shift and + to get a ?. On a US keyboard you typically have to press Shift and / to get ?. Because of this difference in keyboard layouts it is unreliable to use the onkeyup and onkeydown events to detect ?.
If you want to prevent printing char in textbox when the reg matches, you should use keypress. And the reg is: /^[a-zA-Z\x08\?]$/. This works for me.
var regex = /^[a-zA-Z\x08\?]$/;
// OR this one if you want uppercase letters:
var regex = /^[A-Z\x08\?]$/;
$("#regtest").keypress(function(event) {
var _event = event || window.event;
var key = _event.keyCode || _event.which;
alert(key);
key = String.fromCharCode(key);
alert(key);
if(regex.test(key)) {
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
});
Related
I'm writing a keypress event which executes special functions for certain control characters, but inserts any printable character into a string.
this.handle_keypress = function(event) {
let callback = this.control_function[event.key];
if(callback) {
callback.bind(this)(event);
}
else {
this.myText += event.key;
}
}
this.element.addEventListener('keypress', this.handle_keypress.bind(this));
But this will insert the text for unmapped control characters into my string (e.g. 'LeftArrow' or 'Backspace'). How can I tell which characters are printable characters and which are control characters?
Back in the day, I would use event.which or event.charCode, but these are marked as deprecated now.
I cannot use the input event, as far as I know, because I am not typing into a textarea or input field.
I'm running this in Firefox.
There's no immediately way to determine if event.key is a control character.
But given that:
the names of control characters are all currently multiple chars long (e.g., "Escape") and only contain letters and numbers
the length of ASCII characters is 1
non-ASCII characters contain bytes outside the range of [a-zA-Z]
You can make a code to decide between either or:
var letters = [];
elm.addEventListener("keydown", function(e) {
if(e.key.length == 1 || (e.key.length > 1 && /[^a-zA-Z0-9]/.test(e.key))) {
letters.push(e.key);
} else if(e.key == "Spacebar") {
letters.push(" ");
}
}, false);
Check out the documentation for Properties of KeyboardEvent on MDN page:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
For KeyboardEvent.keyCode, they mention:
This attribute is deprecated; you should use KeyboardEvent.key
instead, if available.
For KeyboardEvent.charCode, they mention:
Warning: This attribute is deprecated; you should use
KeyboardEvent.key instead, if available.
So basically "charCode" and "keyCode" have been replaced by simply "code" and "key".
Also, to identify the control characters and avoid printing them, you can try:
Create an array of neglected characters
var unsupportedKeyCharacters = ["Shift", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Enter"];
Call the function to check if entered character is printable
var isSupportedKey = function (keyCharacter) {
var isKeySupported = false;
var unsupportedKeyCharacters = ["Shift", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Enter"];
for (var i = 0; i < unsupportedKeyCharacters.length; i++) {
if (unsupportedKeyCharacters[i] === keyCharacter) {
isKeySupported = false;
break;
}
}
return isKeySupported;
}
Call the function to validate input
I'm trying to use a regular expression to validate the input on a textbox
The expression should allow only numbers, maxmium two decimals, max one comma (,) and one minus symbol in front of the number (optional).
Valid:
0,25
10,2
-7000
-175,33
15555555555555,99
invalid:
9,999
15.03
77,77,77
etc
I'm using ^[-+]?[\d ]+(,\d{0,2})?$
The regex is used in a Jquery code to prevent the user from entering invalid numbers (event.preventDefault()):
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = new RegExp("^[-+]?[\d ]+(,\d{0,2})?$", "g");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Only a part of the regular expression seems to work.
It works with numbers (It does not allow me to enter letters) but it also won't allow commas (,) and the minus (-).
What am I doing wrong?
Edit
Before I used:
if (focused.val().indexOf(',') != -1) {
var number = (focused.val().split(','));
if (number[1] && number[1].length >= 2) {
event.preventDefault();
return;
}
But this gives annoying behavior. As soon as you enter a number with two digits you can't make edits anymore. For example: you can't change 200,50 to 300,50 or 100 300,50. (You get the point). I hoped that a regex could change that somehow.
I think you're massively over-complicating the regex. This should be plenty:
^-?\d+(,\d\d)?$
^ Start of line,
-? Optional minus sign,
\d+ Followed by a bunch of digits,
(,\d\d)? Followed by a comma and 2 digits, which are all 3 optional.
(alternative: (,\d{2})?)
$ End of line.
var regex = /^-?\d+(,\d\d)?$/;
console.log(regex.test('0,25'));
console.log(regex.test('-175,33'));
console.log(regex.test('15555555555555,99'));
console.log(regex.test('9,999'));
console.log(regex.test('15.03'));
console.log(regex.test('77,77,77'));
There you have a regex to validate the input value.
Now, that block of code can be replaced with this:
$("input[name*='TB_mytbx']").on('keypress', function (event) {
var regex = /^-?\d+(,\d\d)?$/;
var value = $(this).val(); // Use the field's value, instead of the pressed key.
if (!regex.test(value)) {
event.preventDefault();
return false;
}
});
For those of you who wanna know, I solved it using this code
$("input[name*='mythingy']").on('keypress', function (event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var value = this.value;
var value = value.replace(value.substring(theEvent.currentTarget.selectionStart, theEvent.currentTarget.selectionEnd), "");
value = [value.slice(0, theEvent.currentTarget.selectionStart), key, value.slice(theEvent.currentTarget.selectionStart)].join('');
var regex = /^[-+]?([\d ]+(,\d{0,2})?)?$/;
if (!regex.test(value)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
});
This question already has answers here:
How to allow only numeric (0-9) in HTML inputbox using jQuery?
(68 answers)
Closed 7 years ago.
I have this script which only allows 0-9 and - characters for negative numbers. However this does not prevent a user from entering 123- for example and it causes errors. Is there a workaround for this? I prefer to stick to JavaScript as much as possible. But I am open to plugins if there is no other way.
It is working well by not allowing other characters such as letter. But I need to prevent users from entering - at the end or any other part aside from the start of the line.
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();
}
}
jsFiddle
JS
// validates the key down event
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
// checks if it is a digit or first char is a -
if (!/^-?\d+/.test(key)) {
console.log(key);
// stops event 100% if it isn't what you want
evt.stopPropagation();
evt.preventDefault();
evt.returnValue = false;
evt.cancelBubble = true;
return false;
}
}
Regex
^-?\d+$
Description
/-?\d+/
^ assert position at start of the string
-? matches the character - literally
Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
\d+ match a digit [0-9]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string
if you like regexp you can try using this
(-|[0-9]?)[0-9]+
It means start is either - or a number. Then followed by only number
You just need to modify your regex a little!
var regex = /-?\d+/
the ? means 0 or 1 and d+ will verify digits only.
Matching only positive and negative integers can be done with the regex /^-?\d+$/.
Explanation:
^ - start of string
-? - optional negative sign {greedy; 0-1}
\d+ - one or more decimal digits, i.e. [0-9] {greedy; 1-infinity}
$ - end of string
Demo:
> /^-?\d+$/.test('42')
true
> /^-?\d+$/.test('-42')
true
> /^-?\d+$/.test('42-')
false
> /^-?\d+$/.test('a42')
false
> /^-?\d+$/.test('42b')
false
My regular expression which allows characters, numbers, dot and underscore is
var numericReg = /^[a-zA-Z0-9\._]+$/;
How could i allow backspace in this reg ex.?
You can use [\b] to match backspace. So, just add it to your character class: -
var numericReg = /^[a-zA-Z0-9._\b]+$/;
Note that you don't need to escape dot (.) in character class. It has not special meaning in there.
See also: -
http://www.regular-expressions.info/reference.html
for more escape sequences, and patterns in Regex.
I'd suggest you rewrite your regex to :
var numericReg = /^[a-zA-Z0-9._]+|[\b]+$/
Or:
var numericReg = /^(?:[a-zA-Z0-9._]|[\b])+$/
Check against 'event.keyCode' and 'value.length' before checking the regular expression.
Keycode 8 = backslash
$('#my-input').on('keypress change', function(event) {
// the value length without whitespaces:
var value_length = $(this).val().trim().length;
// check against minimum length and backspace
if (value_length > 1 && event.keyCode != 8) {
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;
}
}
}
The optimal solution for this problem is to check the value of textbox >0 before validating. This will help to solve error showing while pressing backspace in an empty textbox..!!
I also made a input type text that accept only numbers(non decimal) and backspace keyboard. I notice that putting [\b] in regular expression is not needed in non Firefox browser.
var regExpr = new RegExp("^[0-9,\b][0-9,\b]*$");
I met some trouble with a javascript.
In fact I have in my database many records that are abreviations and ther equivalent,
for example, replace tel => telephone etc...
So I have this function
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
console.log(code);
if (code == 'tel'){
var input = this.value;
input = input.substr(0, input.length -1);
console.log(input);
input += 'tel';
this.value = input;
}
});
Actualy this does not work the trouble is that I do not have aby mistakes
in the console of javascript.
Anykind of help will be much appreciated.
Kind regards.
SP.
This should work:
$('#tags').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
var input = this.value;
if (input.indexOf('tel') != -1) {
this.value = this.value.replace(/\btel\b/gi,'telephone');
}
});
Here is a fiddle
When using keyup() the event handler only returns the keycode of the pressed key. For instance an x results in e = 88.
Use $("#tags").val() to get the value of the input element.
the keyCode or which property doesn't return a string, or even a single char. It returns the key code that represents the key that was struck by the client. If you want to get the corresponding char: String.fromCharCode(e.which || e.keyCode);.If the user hit on the a key, for example, the keycode will be 97, String.fromCharCode(97) returns a.
If you want to know weather or not the current value of the element contains the abreviation: tel, what you'll need to do is this:
$('#tags').keyup(function(e)
{
this.value = this.value.replace(/\btel\b/gi,'telephone');
});
This is untested and very likely to need some more work, but AFAIK, you want to replace all occurrences of tel by telephone. The expression I use /\btel\b/ replaces all substrings tel, provided they are preceded and followed by a word-boundary (to avoid replacing part of a word). Not that the end of a string and a dash are both considered to be word boundaries, too. If I wanted to type television, I'd end up typing telephoneevision. To avoid this, you'll need a slightly more complex expression. here's an example how you can avoid JS from treating a dash as a boundary, just work on it to take string-endings into account, too
Update
Perhaps this expression isn't quite as easy as I thought, so here's what I'd suggest you use:
this.value = this.value.replace(/(?:(\-?\b))tel(?:(\b\-?.))/gi,function(all,b1,b2)
{
if (b1 === '-' || b2.charAt(0) === '-')
{//dash, don't replace
return all;
}//replace
return b1 + 'telephone' + b2;
});
Input: I need a tel, quickly ==> I need a telephone, quickly
I need a tel ==> I need a tel (if the user is still typing, don't replace, he could be typing telescope, replace on submit or on blur)
I want to book a hostel for tonight ==> I want to book a hostel for tonight
Visit Tel-Aviv ==> Visit Tel-Aviv
When using keypress this way the code variable will contain the character code of the pressed character. Not the string of chars like the expected 'tel'. You could use onkeyup / onchange event and check the val() of the input element and use replace() to change the abbreviation to the intended string.
$('#tags').keyup(function(e){
var elem = $(this);
var input = elem.val();
// input = input.substr(0, input.length -1); // This might not be necessary
console.log(input);
// do the replacement
input = input.replace('tel','telephone');
elem.val(input);
}
});
Use replace method for replacing a word in string.
eg:
var str = "This is AIR";
var newstr = str.replace("AIR", "All India Radio");
console.log(newstr);