allow input with decimal places upto 3 - javascript

I want to allow only integers and floats (upto 3 decimal places) in a text box, how can I achieve this using javascript?
Valid values are
1234
12.3
12.314
1.11
0.4
Not valid
1.23456
abcd or any other character

Based on the comment that you need to also match ".1" you need to add a conditional with the first part of the regular expression.
var re = /^(\d+)?(?:\.\d{1,3})?$/;
Rough test suite - jSFiddle

You can use a regular expression to do this:
/^\d+(?:\.\d{1,3})?$/
That's the start of the string (^), one or more digits (\d+), optionally followed by a . and between 1 and 3 digits ((?:\.\d{1,3})), then the end of the string ($).
To compare it to the value of an input, you'd do something like this:
var re = /^\d+(?:\.\d{1,3})?$/;
var testValue = document.getElementById('id-of-input').value;
if(re.test(testValue)) {
// matches - input is valid
}
else {
// doesn't match - input is invalid
}
Take a look at this jsFiddle demo.

use regular expression to validate your input field , regular rexpression is as below
^[0-9]+(?:\.[0-9]{1,3})?$

Try this:
var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));
Check Fiddle http://jsfiddle.net/8mURL/1

Related

Extract number between slashes

This is my setup:
var test =
"http://tv.website.com/video/8086844/randomstring/".match(/^.+tv.website.com\/video\/(.*\d)/);
I want to extract the video id(8086844) and the regex does work, however when another digit is added after the "randomstring", it also matches the 8086844 + randomstring + other number.
What do I have to change in order to always get just the video id.
Try this regex
/^.+tv.website.com\/video\/([\d]+)/
It will search every digit character after ...video\ word and then give all the concordant digits thereafter till any non-digit character comes
The problem is the (.*\d) part, it looks for a greedy string ends with a digit, instead you need a continues series of digits after video/, it can be done via (\d+)
change it to
var test = "http://tv.website.com/video/8086844/randomstring/dd".match(/^.+tv.website.com\/video\/(\d+)/)[1];
var test = "http://tv.website.com/video/8086844/randomstring/8";
test = test.match(/^.+tv.website.com\/video\/(\d+)/);
console.log(test);
console.log(test[1]);
Output
[ 'http://tv.website.com/video/8086844',
'8086844',
index: 0,
input: 'http://tv.website.com/video/8086844/randomstring/8' ]
8086844
You are almost there. We know that, its going to be only numbers. So instead of .*\d we are gathering only the digits and grouping them using parens.
This is the simplest of all:
Use substr here
test.substr(28,7)
Fiddle
To extract out the id from your string test:We use substr(from,to)

Determine if a string is only numbers or a comma

How can I determine if a string contains only numbers or a comma?
var x = '99,999,999';
var isMatch = x.match('/[\d|,]/');
The above always returns null.
To be a little more exact:
/^\d{1,3}(?:,\d{3})*$/
Only matches when the number is delimited by a comma after every 3rd digit from the right. (This doesn't account for decimals)
Try this: /^[\d,]+$/ Note that this will not tell you if the number is formatted correctly (i.e. ,99, will be accepted just as 99 or 9,999).
/^(?:\d{1,3}(?:,\d{3})*$|^\d+$)/ while more complex, this regex will test to see if the number is a properly formatted number (it won't accept ,,1,,,1,1111,,1,1,1 only 1,11,111,1,111,1111 etc.)

how to use javascript to check if the first character in a textbox is a number?

I'm making a simple form and having a textbox for street address....
All I want to do is check if the first value entered is a number or not.
How can I do it?
if(document.forms[0].elements[2].value.
that is all I have now but I'm not sure what I should add to it to check the first character only.
As you said in your question you want to check for the first character only, you can use charAt function for string to check whether the first character is from 0 to 9 or any other check you want for the first character
Possible solution
var firstChar = document.forms[0].elements[2].value.charAt(0);
if( firstChar <='9' && firstChar >='0') {
//do your stuff
}
This can simply use isNaN. Just put a bang before it to check if it is a number, instead of isNaN's normal use of checking if it isn't a number, like so:
var val = document.forms[0].elements[2].value;
if (!isNaN(val.charAt(0))){ //If is a number
//Stuff
}
This also goes with numbers as strings, so need to worry about quotes or any of that hoo ha.
You can use if (document.forms[0].elements[2].value.match(/^\d+/)) to check if the beginning of the field is composed by numbers.
It will match for:
0 - valid
1 - valid
1a - valid
1 a - valid
1234567 - valid
a - invalid
a1 - invalid
Literally anything that start with numbers.
You can extend its functionality to if (document.forms[0].elements[2].value.match(/^\d+ +.+/))
In this form it will now require that its a number, plus one or more spaces, followed by anything else.
0 - invalid
1 - invalid
1(space) - invalid
1 1 - valid
1 a - valid
12345 abcdef - valid
Read more about Regular Expressions to elaborate complexier checkings.
But remember first that not every address has numbers, and most countries in the world don't use this format of writing addresses. As for the address field, I believe you should leave it open to be written in however format the user wish.

Remake of this regexp

I have this regular expression to help me validate a form input.
var nrExp = /^\d{6}\-\d{4}$/;
This allows only 10 digits, where the last 4 digits are separated with a "minus sign".
012345-6789
I need to make it also allow it without the minus-sign AND with a space instead of a minus-sign:
0123456789
012345 6789
How can I remake this regexp to allow what I want?
Thanks
/^\d{6}[- ]?\d{4}$/
You don't need to escape the minus sign inside the brackets, as it does not give a range.
/^\d{6}[ \-]?\d{4}$/
var nrExp = /^\d{6}\[\- ]?\d{4}$/;
That should do it - either a blank space or a dash, made optional by the ?
var re = /^\d{6}[\- ]?\d{4}$/
console.log(re.test('012345-6789'));
console.log(re.test('012345 6789'));
console.log(re.test('0123456789'));
Sure. You just want to make the minus optional, along with a couple of other characters.
Try this one:
var nrExp = /^\d{6}(\-| )?\d{4}$/;
Notice the ? after the (\-| ). This allows that match portion to be optional.

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources