Some parts of my regular expression not working - javascript

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();
}
});

Related

How to modify a text inputbox so that it accepts only certain characters?

I've an input box in which I only want to allow 0-9, (, ), -, ., and (space) characters. After researching and picking up code from different tutorials, I managed to (I think) come up with the required regex pattern.
But it isn't working and always returning false even if the character typed is one from the above. The code that I've with me is as follows:
var regex = new RegExp("/[0-9.\(\)\b\ -]/", "gi");
if(regex.test(str)){
return true;
} else {
console.log('failed');
return false;
}
I'm having failed printed in the console every single time. What am I missing here?
EDIT: Demo (It seems to be working here)
EDIT2: JSFIDDLE
UPDATE:
I think my question is being misinterpreted here. I probably didn't do a good job at describing my use case. Well here it is then:
In my textbox, I only want to allow the above mentioned characters. So if a user types "23a" in the textbox, it should only allow "23" and "a" shouldn't be allowed to be typed
new RegExp() is superfluous here, just use regex literal notation (see note #2 below).
You want to anchor the expression to the beginning (^) and the end ($) of the string, to make sure it applies to the entire string. That's what you have tried to accomplish with g, but that is not what g does.
The i (case-insensitive) modifier is not necessary either, the pattern does not contain letters.
function isValidChar(str) {
return /^[0-9.() -]$/.test(str);
}
$(function(){
$('#p_zip').on('keypress', function (e) {
return isValidChar(String.fromCharCode(e.keyCode));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Here is a version that works entirely without regex, comparing the keycode is enough.
function filterNumericKey(e) {
var c = e.keyCode;
return (c >= 48 && c <= 57) || // "0" .. "9"
c === 32 || // " "
c === 40 || // "("
c === 41 || // ")"
c === 45 || // "-"
c === 46; // "."
}
$(function(){
$('#p_zip').on('keypress', filterNumericKey);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="p_zip">
Notes
The following is an anti-pattern, in any language, not just JS:
if (booleanCondition) {
return true;
} else {
return false;
}
Just use return booleanCondition; directly instead.
If you want to use new RegExp() instead of a regex literal, you
must not use forward slashes to delimit your expression
must escape any backslashes, just like you would do in any other JavaScript string
Beware that both solutions will not check text that is pasted or dropped on the input element. You might want to write checks for that as well.
I managed to solve it. I was making a rookie mistake. I needed to return false on keypress event instead of keyup. And I was also taking the value of the textbox into account instead of the event object.
function isNumber(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^[0-9\.\b\(\) -]+$/;
if (!regex.test(key)) {
return false;
} else {
return true;
}
}

Javascript only allow numbers at end of text [duplicate]

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

How to regex match entire string instead of a single character

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'));

jQuery only allow numbers,letters and hyphens

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 -]+$"

regular expression in javascript which allows backspace

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]*$");

Categories