Reputation: 123
How can I test valid numbers in the format of?
Accepted:-
100,000
100,000.00
100,000.0000
10,000,000.00
0.00
10000.000
Not Accept:-
,100,00,.
,.100.00
100.00,00
100..,,
( only allow single dot(decimal point) and multiple commas, but the number should not start or end with comma or dot, there should not be any improper use of comma and dots as shown above) I tried the following java script for it but it couldn’t solve my issue. Can anyone update my function…
function isNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
if (key.length == 0) return;
var regex = /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
//var regex = /^[0-9.,]+$/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Upvotes: 1
Views: 2726
Reputation: 1180
If I'm not mistaken, the problem is not (only?) with the regex, but rather with the event handler: It's accepting a single character, creating a String
from this single character, and then matching that against the regex.
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
will never give you a string. If you must use a character-grabbing event, you'll have to use a global variable to accumulate the string over several keystrokes.
The other alternative is to use a textfield and validate the field content when the cursor leaves the field.
If you need assistance with that, please add information which event is handled by isNumber
and what interaction you want to achieve (keystroke handling or text field or whatever else).
EDIT:
You'll have to find out from the keystroke event which field the user is in. Get the text value of that field, and match the regex against the field value, not against the single keystroke.
The tricky thing is the first one, I figure. Either you create an event handler only for the text field you need to validate, or (if there's several fields to validate) you create the handler for a DOM element containing all these fields, and look at event.target
(and hopefully the browsers you target are compliant enough to support this), which gives you the DOM element the event was triggered.
Upvotes: 0
Reputation: 8332
Try
^(\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+|)$
Expl.: Match one to three digits. Then allow any number of groups with a comma followed by three digits. If no match on previous, try any number of digits (more than one). Then allow optional decimals. Change to
^(\d{1,3}(?:,\d{3})*|\d+)\.\d+$
if decimals are mandatory.
Check out regex101
Regards
Upvotes: 1
Reputation: 3039
Try this :
var numRegex = /^(?:[1-9]\d{0,2}(?:,\d{3})*|0)(?:\.\d+)?$/;
numRegex.test("1,000,000");
numRegex.test("100,000");
numRegex.test("100,000.00");
Upvotes: 4