I am trying to build a regex expression with this requirement .
Requirement :
Max length - 5(inc decimal dot if is a decimal number)
Decimal precession - max 2 digits (if it is a decimal numer ).
Number - need not to be a decimal number (not mandatory)
Code:
<script>
function myFunction() {
var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
var num = 12345.52; // i will test here indiffernt ways
var n = regexp.test(num)
document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>
Output should look like :
12345.52 -->It should return false as length is 8 inc dot but it returns true
123456.52 --> false . I came to know d{0,5} is looking for before decimal
12.45 --> true . Perfect one (length 5 , precession 2 )
12345 --> true . Perfect one (length 5 , precession- not madatory)
I am hoping to build a regex expression satisfies all the above scenarios .
Reference : Click Here
You could try the below regex which uses positive lookahead assertion.
^(?=.{1,5}$)\d+(?:\.\d{1,2})?$
DEMO
Explanation:
^ Asserts that we are at the start.
(?=.{1,5}$) Asserts that the length must be from 1 upto 5.
\d+ Allows one or more digits.
(?:\.\d{1,2})? Optional decimal part with the allowable digits after the decimal point must be one or two.
$ Asserts that we are at the end of the line.
Related
I am trying to write a regex for the following condition:
Allow to enter up to 1 decimal place and if I start with integer 0; the next has to be decimal otherwise any other number entered will remove the 0(integer)
The regex that I have provided is /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/ it accepts 1 decimal place but I am unable to achieve the remaining part.
Edit 1
passed numbers -->
1.3
4.5
0.4
Failed numbers ---->
004
If number starts with 0, next character must be a decimal only
Eg,
0.5 is a pass
005 is a failed
try this:
^([1-9]+\d*.?\d?)|^(0.\d)
If not, see comments and try to better exemplify
Try this regex:
^([0]{1}(\.[0-9]+))$|^([1-9]{1}|[1-9][0-9]+)$
ADJUSTED REGEX:
I have now adjusted the regex as required: all numbers that start with 0 MUST follow a comma, e.g. 0.2 or 0.0002 is accepted. 02 or 00002 is NOT accepted
OK, you want find integer number not start with 0, and find decimal?
Your code is: /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/
Case 1: integer [1-9]\d*
Case 2: decimal
//match 5.0
patt = \d+\.\d+
//Match 5.1xxxx, 5.2xxx, etc.
patt = \d+\.[1-9]\d*
//match 5.0xxx
patt = \d+\.0\d+
//combine all of them
patt = ([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)
//Final
patt = /(^$)|(([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)?$)/
I will explain some pattern above:
\d == [0-9] //match 1 character between 0 and 9
\d* == \d{0,} //match 0 or more character
\d+ == \d{1,} //match at least one character
What is the regular expression for a decimal with a precision of 2?
Valid examples:
123.12
2
56754
92929292929292.12
0.21
3.1
Invalid examples:
12.1232
2.23332
e666.76
The decimal point may be optional, and integers may also be included.
Valid regex tokens vary by implementation. A generic form is:
[0-9]+(\.[0-9][0-9]?)?
More compact:
\d+(\.\d{1,2})?
Both assume that both have at least one digit before and one after the decimal place.
To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):
^\d+(\.\d{1,2})?$
To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:
^(\d+(\.\d{0,2})?|\.?\d{1,2})$
Added
Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.
Added
Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.
^[0-9]+(\.[0-9]{1,2})?$
And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:
^ # Start of string
[0-9]+ # Require one or more numbers
( # Begin optional group
\. # Point must be escaped or it is treated as "any character"
[0-9]{1,2} # One or two numbers
)? # End group--signify that it's optional with "?"
$ # End of string
You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.
Also, here is the simple Python script I used to check it:
import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]
assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0
To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:
-?(0|([1-9]\d*))(\.\d+)?
For numbers that don't have a thousands separator, I like this simple, compact regex:
\d+(\.\d{2})?|\.\d{2}
or, to not be limited to a precision of 2:
\d+(\.\d*)?|\.\d+
The latter matches
1
100
100.
100.74
100.7
0.7
.7
.72
And it doesn't match empty string (like \d*.?\d* would)
I use this one for up to two decimal places:
(^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$)
passes:
.25
0.25
10.25
+0.25
doesn't pass:
-.25
01.25
1.
1.256
^[0-9]+(\.([0-9]{1,2})?)?$
Will make things like 12. accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9] can be replaced with \d, but I guess it’s more readable this way.
Try this
(\\+|-)?([0-9]+(\\.[0-9]+))
It will allow positive and negative signs also.
preg_match("/^-?\d+[\.]?\d\d$/", $sum)
In general, i.e. unlimited decimal places:
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.
Main answer is WRONG because it valids 5. or 5, inputs
this code handle it (but in my example negative numbers are forbidden):
/^[0-9]+([.,][0-9]{1,2})?$/;
results are bellow:
true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2"
true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true =>
"1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false =>
"0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" /
true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true =>
"81,3" / true => "7" / true => "7.654"
Won't you need to take the e in e666.76 into account?
With
(e|0-9)\d*\d.\d{1,2)
adding my answer too, someone might find it useful or may be correct mine too.
function getInteger(int){
var regx = /^[-+]?[\d.]+$/g;
return regx.test(int);
}
alert(getInteger('-11.11'));
This worked with me:
(-?[0-9]+(\.[0-9]+)?)
Group 1 is the your float number and group 2 is the fraction only.
I tried one with my project.
This allows numbers with + | - signs as well.
/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
Chrome 56 is not accepting this kind of patterns (Chrome 56 is accpeting 11.11. an additional .) with type number, use type as text as progress.
This will allow decimal with exponentiation and upto 2 digits ,
^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$
Demo
function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.
Thanks... :)
I am trying to validate a number field integer and decimal with regular exp. its working fine for all the cases except one digit number:-
$(document).ready(function(){
$("#quantity").on('blur',function(){
var quantity = $('#quantity').val()
var pattern = /^-?\d+\.?([0-9]{1,2})$/;
alert(pattern.test(quantity))
})
})
output:
1 ---> false (why?)
-
9 ---> false (why?)
5.87 -->true (fine)
12.35 ---> true (fine)
12.344 --->false (fine)
2323.34 --->true (fine)
for 1 to 9 its alerting True but i need it as false
You have both \d+ and [0-9]{1,2} in the string, which implies there must be at least 2 digits in the string (with an optional decimal in between).
If you want the entire decimal part to be optional, just surround it with parentheses and add a ? quantifier:
/^-?\d+(\.[0-9]{1,2})?$/
What I want is, there is a textbox with maximum length of 5. The values allowed are..
any integer // for example 1, 3, 9, 9239 all are valid
real number, with exaclty one point after decimal // eg. 1.2, 93.7 valid and 61.37, 55.67 invalid
it is also allowed to enter only decimal and a digit after that, that is .7 is valid entry (would be considered as 0.7)
I found this page, http://www.regular-expressions.info/refadv.html
So what I thought is that
There is a digit
If there is a digit and a decimal after that, there must be one number after that
If there is no digit there must be a decimal and a digit after that
So, the regex I made is..
a single digit one or more => /d+
an optional decimal point followed by exactly one digit => (?:[.]\d{1})?
if first condition matches => (?(first condition) => (?((?<=\d+)
then, match the option decimal and one exact digit =>(?((?<=\d+)(?:[.]\d{1})?
else => |
find if there is a decimal and one exact digit => (?:[.]\d{1}){1}
check the whole condition globally => /gm
overall expression =>
(?(?<=\d+)(?:[.]\d{1}){1}|(?:[.]\d{1}){1})+/gm
But it doesn't outputs anything..
Here's the fiddle
http://jsfiddle.net/Fs6aq/4/
ps: the pattern1 and pattern2 there, are related to my previous question.
Maybe you are complicating things too much. I did a quick test and unless I'm missing something this regex seems to work fine:
/^\d*\.?\d$/
Demo: http://jsbin.com/esihex/4/edit
Edit: To check the length you can do it without regex:
if ( value.replace('.','').length <= 5 && regex.test( value ) ) {
...
}
Notice that I used replace to remove the dots so they don't count as characters when getting the length.
You can try the following pattern:
/^\d{0,4}\.?\d$/
It seems to fulfil all your requirements:
> /^\d{0,4}\.?\d$/.test(".4")
true
> /^\d{0,4}\.?\d$/.test(".45")
false
> /^\d{0,4}\.?\d$/.test("1234.4")
true
> /^\d{0,4}\.?\d$/.test("12345.4")
false
> /^\d{0,4}\.?\d$/.test("12345")
true
> /^\d{0,4}\.?\d$/.test("123456")
false
This pattern assumes that the number can have a maximum of five digits and an optional decimal point.
If the maximum length of five includes the optional decimal point then the pattern is slightly more complex:
/^(?:\d{1,5}|\d{0,3}\.\d)$/
The first part of the group deals with integer numbers of the required length, the second option of the group deals with real numbers which maximum length (including the decimal point) is five.
Consider this code:
var checkedString = "45.3 fsd fsd fsdfsd 673.24 fsd63.2ds 32.2 ds 32 ds 44 fasd 432 235f d653 dsdfs";
checkedString = " "+checkedString;
var results = checkedString.match(/[\s]{1}(\d+\.*\d{1})(?![\d\.\w])+/gm);
results.map(function(result) {
return result.trim();
});
Couldn't make it in other way because in JS (?<= (lookbehind) regexp is not working.
This will be returned:
["45.3","32.2","32","44","432"]
So probably it's what you've expected.
I don't know what are you trying to do with those conditionals in your regex. I also looked at your jsfiddle, which outputs nothing for me. But I made a two versions of a regex that matches the correct values for the textbox, which are ^(?!(.{6,}))(?:[1-9]\d*)*(?:\.\d*[1-9])?$ and ^(?!(.{6,}))(?:\d*)*(?:\.\d*)?$.
The first disallows to start with zero, or end with zero after the decimal.
Comment if you need explanation of the regex.
Please help with me writing a JavaScript Validation for currency/money field.
So please provide any regular expressions if u have :)
Also, for my region, don't need any currency symbols like '$' in the field.
Only decimals are to be included for validation as special chars., along with numbers.
You could use a regexp:
var regex = /^\d+(?:\.\d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
alert("Number is valid");
If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:
var numStr = "123.20";
var numNum = +numStr; // gives 123.20
If the number string is invalid, it will return NaN (Not a Number), something you can test for easily:
var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
alert("numNum is not a number");
It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2) to round to 2 decimal places. parseFloat is much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc") would yield 123.
I built my answer from the accepted answer.
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
^[1-9] The number must start with 1-9
\d* The number can then have any number of any digits
(...)$ look at the next group from the end (...)$
(...)?(...)? Look for two groups optionally. The first is for the comma, the second is for the decimal.
(,\d{3}){1} Look for one occurance of a comma followed by exactly three digits
\.\d{0,2} Look for a decimal followed by zero, one, or two digits.
This regex works off of these rules:
Valid values are numbers 0-9, comma and decimal point.
If a customer enters more than one decimal point or more than one comma, the value is invalid and will not be accepted.
Examples of invalid input values
1.2.3
1,2,4
Examples of valid input values
1.23
1,000
3967.
23
1.2
999,999.99
An example can be seen here:
http://jsfiddle.net/rat141312/Jpxu6/1/
UPDATE
by changing the [1-9] in the regex to [0-9] any number less than 1 can also be validated. Example: 0.42, 007
/[1-9]\d*(?:\.\d{0,2})?/
[1-9] - must start with 1 to 9
\d* - any number of other digits
(?: )? - non capturing optional group
\. - a decimal point
\d{0,2} - 0 to 2 digits
does that work for you?
or maybe parseFloat:
var float = parseFloat( input );
let amount = document.querySelector('#amount'), preAmount = amount.value;
amount.addEventListener('input', function(){
if(isNaN(Number(amount.value))){
amount.value = preAmount;
return;
}
let numberAfterDecimal = amount.value.split(".")[1];
if(numberAfterDecimal && numberAfterDecimal.length > 3){
amount.value = Number(amount.value).toFixed(3);;
}
preAmount = amount.value;
})
<input type="text" id="amount">
For me its working fine for Indian currency in INR
var regex = /^[1-9]{0,2}(,{0,1})(\d{2},)*(\d{3})*(?:\.\d{0,2})$/;
var a = '1,111.11';
regex.test(a);
Now I use this:
let func = function (vStr) {
let v0 = Number(vStr);
let v1 = Number(v0.toFixed(2));
return v0 === v1;
};
Note that, NaN === NaN returns false. Maybe some substitution for '$' and ',' before parsing is needed, for other cases.
And there is a problem of precision for very large number, longer than 16 digits. As well as values of '0x3a', '68n' is considered valid.
Nowadays, <input> of type="number", with step='.01' may be more proper.