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]*$");
Related
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
I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.
Now the problem is it gives the following result:
r = /[\u0600-\u06FF]/
r.test("abcd") // false - correct
r.test("##$%^") // false - correct
r.test("س") // true - correct
r.test("abcd$$#5س") // true - should be false
r.test("abcdس") // true - should be false
If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?
You need to add ^ and $ anchors to the regular expression, as well as a + to allow multiple characters.
Try this:
/^[\u0600-\u06FF]+$/
I'm not sure if "Arabic spaces" that you mentioned are included in the character range there, but if you want to allow white space in the string then just add a \s inside the [] brackets.
You can explicitly allow some keys e-g: numpad, backspace and space, please check the code snippet below:
function restrictInputOtherThanArabic($field)
{
// Arabic characters fall in the Unicode range 0600 - 06FF
var arabicCharUnicodeRange = /[\u0600-\u06FF]/;
$field.bind("keypress", function(event)
{
var key = event.which;
// 0 = numpad
// 8 = backspace
// 32 = space
if (key==8 || key==0 || key === 32)
{
return true;
}
var str = String.fromCharCode(key);
if ( arabicCharUnicodeRange.test(str) )
{
return true;
}
return false;
});
}
// call this function on a field
restrictInputOtherThanArabic($('#firstnameAr'));
How can I remove everything but numbers,letters and hyphens from a string with jQuery?
I found this code which allows only alphanumerical characters only but I'm not sure how I would go about adding a hyphen.
$('#text').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$".
Note that the hyphen is escaped using \, otherwise it is used to specify a range like a-z (characters from a to z).
This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :
// The function you currently have
$('#text').keypress(function (e) {
var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
// the addition, which whill check the value after a keyup (triggered by Ctrl+V)
// We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});
Since there is so much attention on including a hyphen within a character class amongst these answers and since I couldn't find this information readily by Googling, I thought I'd add that the hyphen doesn't need to be escaped if it's the first character in the class specification. As a result, the following character class will work as well to specify the hyphen in addition to the other characters:
[-a-zA-Z0-9]
I think you can just put a hyphen inside the square brackets.
"^[a-z A-Z 0-9 -]+$"
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();
}
});