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
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();
}
});
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 -]+$"
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]*$");
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript percentage validation
I want to allow 0.00 to 100.00 only.
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.replace(/[^\d.d]+/g, '');
}
}
<asp:textbox id="txtrate" runat="server" Width="200px" onkeyup= "javascript:ValidateText(this)"></asp:textbox>
It allows 0-9.0-9. Help me please. Thanks
Now this is some popular question!
This should do:
function validate(s) {
return s.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/) != null;
}
var test = [
'3.0',
'5',
'99.99',
'100',
'100.00',
'100.01',
'101',
'0.3',
'.5',
'0.567',
];
for (i=0; i<test.length; ++i) {
WScript.StdOut.WriteLine(test[i] + ' => ' + validate(test[i]));
}
Outputs:
3.0 => true
5 => true
99.99 => true
100 => true
100.00 => true
100.01 => false
101 => false
0.3 => true
.5 => false
0.567 => false
Edit: the regexp can be shortened a bit without changing its meaning, credits to 6502
/^(100(\.00?)?|[1-9]?\d(\.\d\d?)?)$/
This expression should allow only what you are asking for
/^[1-9]?\d(\.\d\d?)?|100(\.00?)?)$/
Meaning is
^ start of string
( start of sub-expression ("or" between two possibilities)
[1-9]? an optional non-zero digit
\d followed by a digit
(\.\d\d?)? optionally followed with a dot and one or two digits
| or
100 the string "100"
(\.00?)? optionally followed by a dot and one or two zeros
) end of sub-expression
$ end of string
Try this one
^(?:\d{1,2}(?:\.\d{1,2})?|100(?:\.0?0)?)$
See it here on Regexr
(?:) are non capturing groups, that means the match from this group is not stored in to a variable.
\d{1,2} matches 1 or 2 digits
(?:\.\d{1,2})? This is optional, a . followed by 1 or two digits
or
100(?:\.0?0)?) matches 100 optionally followed by 1 or 2 0
^ matches the start of the string
$ matches the end of the string
Those two anchors are needed, otherwise it will also match if there is stuff before or after a valid number.
Update:
I don't know, but if you want to disallow leading zeros and numbers without two digits in the fraction part, then try this:
^(?!0\d)(?:\d{1,2}(?:\.\d{2})|100\.00)$
I removed the optional parts, so it needs to have a dot and two digits after it.
(?!0\d) is a negative lookahead that ensures that the number does not start with a 0 and directly a digit following.
How about:
var x = '76', // (i.value)
testx = Number(x.match(/\d+/)[0]);
console.log(testx>=0 && testx<=100);
Applied in your function:
function ValidateText(i) {
var val = i.value;
if (val.length>0) {
var test = Number(val.match(/\d+/)[0]);
return test >=0 && test <= 100;
}
return false;
}
Use this regex: ^(?:100(?:\.0{1,2})?|[0-9]{1,2}(?:\.[0-9]{1,2})?)$
Use this:
function ValidateText(i)
{
if(i.value.length>0)
{
i.value = i.value.match(/[1?\d{1,2}\.\d\d]/)[0];
}
}
instead of replacing all that is not (0.00 - 100.00) (as it seems to me you are trying to do), I match the allowed strings and replace the original variable content with only the matched string.
Keep in mind that this will work if you only have 1 match. If you have more, you have to trick a bit the expression and decide how to concatenate the array of results.
I don't actually see this as primarily a regex problem. I'd probably write this, particularly if you want informative error messages out it:
HTML:
<input id="percentValue" type="text" size="20">
<input type="button" value="Check" onclick="checkPercent()">
Javascript:
function checkPercent() {
var o = document.getElementById("percentValue");
var val = o.value;
if (val.length == 0) {
alert("Empty value");
return;
}
var index = val.search(/[^0-9\.]/);
if (index != -1) {
o.selectionStart = o.selectionEnd = index;
alert("Invalid characters");
return;
}
if (val.match(/\./g).length > 1)
{
alert("Number must be of the form n.n");
return;
}
var floatVal = parseFloat(val);
if (floatVal < 0 || floatVal > 100)
{
alert("Value must be between 0.00 and 100.00");
return;
}
alert("Valid value of: " + floatVal.toFixed(2));
}
jsfiddle here: http://jsfiddle.net/jfriend00/rDbAp/