I want to allow only the four decimal values followed by numbers and can allow negative numbers.
$(document).on("keyup", "input[name='measuredqty']", function(){
if (/\D/g.test(this.value)){
this.value = this.value.match(/^-\d+\.?\d{0,4}/);
}
});
This regular expression should do what you want:
/^-?\d+(\.\d{0,4})?$/
^ forces starting at the beginning of the string
-? allows an optional minus
\d+ allows one or more digits
(\.\d{0,4})? says the decimal part is optional, with up to 4 digits
$ forces finishing at the end of the string
Related
I'm having a regex problem when input
That's the requirement: limit 10 characters (numbers) including dots, and only 1 dot is allowed
My current code is only 10 characters before and after the dot.
^[0-9]{1,10}\.?[0-9]{0,10}$
thank for support.
You could assert 10 chars in the string being either . or a digit.
Then you can match optional digits, and optionally match a dot and again optional digits:
^(?=[.\d]{10}$)\d*(?:\.\d*)?$
The pattern matches:
^ Start of string
(?=[.\d]{10}$) Positive lookahead, assert 10 chars . or digit till the end of string
\d* Match optional digits
(?:\.\d*)? Optionally match a `. and optional digits
$ End of string
See a regex demo.
If the pattern should not end on a dot:
^(?=[.\d]{10}$)\d*(?:\.\d+)?$
Regex demo
The decimal point throws a wrench into most single pattern approaches. I would probably use an alternation here:
^(?:\d{1,10}|(?=\d*\.)(?!\d*\.\d*\.)[0-9.]{2,11})$
This pattern says to match:
^ from the start of the number
(?:
\d{1,10} a pure 1 to 10 digit integer
| OR
(?=\d*\.) assert that one dot is present
(?!\d*\.\d*\.) assert that ONLY one dot is present
[0-9.]{2,11} match a 1 to 10 digit float
)
$ end of the number
You can use a lookahead to achieve your goals.
First, looking at your regex, you've used [0-9] to represent all digit characters. We can shorten this to \d, which means the same thing.
Then, we can focus on the requirement that there be only one dot. We can test for this with the following pattern:
^\d*\.?\d*$
\d* means any number of digit characters
\.? matches one literal dot, optionally
\d* matches any number of digit characters after the dot
$ anchors this to the end of the string, so the match can't just end before the second dot, it actually has to fail if there's a second dot
Now, we don't actually want to consume all the characters involved in this match, because then we wouldn't be able to ensure that there are <=10 characters. Here's where the lookahead comes in: We can use the lookahead to ensure that our pattern above matches, but not actually perform the match. This way we verify that there is only one dot, but we haven't actually consumed any of the input characters yet. A lookahead would look like this:
^(?=\d*\.?\d*$)
Next, we can ensure that there are aren't more than 10 characters total. Since we already made sure there are only dots and digits with the above pattern, we can just match up to 10 of any characters for simplicity, like so:
^.{1,10}$
Putting these two patterns together, we get this:
^(?=\d*\.?\d*$).{1,10}$
This will only match number inputs which have 10 or fewer characters and have no more than one dot.
If you would like to ensure that, when there is a dot, there is also a digit accompanying it, we can achieve this by adding another lookahead. The only case that meets this condition is when the input string is just a dot (.), so we can just explicitly rule this case out with a negative lookahead like so:
(?!\.$)
Adding this back in to our main expression, we get:
^(?=\d*\.?\d*$)(?!\.$).{1,10}$
What could I use as a regex that validates floating point numbers?
The numbers could be negative and cannot start by 0 (unless it is a real 0, or a 0 followed by decimal points such in 0.00123)
On the other hand, the regex should validate partial/uncompleted numbers. For example:
''(empty string) is valid
- is valid (it could still be a valid number with appropiate user input)
0 is valid (as 0.1 could be valid)
0.0 is valid, for the same previous reason
-0.000 is valid
-01 is not valid
.2 is not valid
I tried with this regexp:
^(-|-?0\.?[0-9]*|-?[1-9][0-9]*\.?[0-9]*|)$
It allows me to discard all non-numeric values and still allow fractional values, but how to implement the possibility that the user cannot enter numbers in the format -0232, but can enter -0.232
If I get it right, you want a regex that validates "could-be-a-future-decimal" numbers. So (empty string) -, -0, 0 and 0.... should be valid.
You may use this regex:
^-?(?:(?!0\d)\d+\.?\d*)?$
You have a demo here.
Explained:
^ # Start of string
-? # an optional minus
(?: # non-capturing group
(?!0\d) # whatever comes next, it cannot be 0 + number
\d+ # at least one number
\.? # optional dot
\d* # any quantity of numbers
)? # previous group is optional
$
Also, bear in mind that the previous thing is a regex object. So you should try to use it like this in javascript:
/myregex/
However, javascript also allows using string-based regexes (which by your comments it seems that is what you want...)
In that case you can use the new RegExp syntax. However, bear in mind that since you'll be using a string, you need to scape any characters a string should scape.
For example, you may use:
function return_some_regex_string() {
// NOTE backslashes had to be scaped since this is a string,
// not a real regex object
return '^-?(?:(?!0\\d)\\d+\\.?\\d*)?$';
}
console.log("0.123".match(new RegExp(return_some_regex_string())));
console.log("-03233".match(new RegExp(return_some_regex_string())));
console.log("333-3334".match(new RegExp(return_some_regex_string())));
But, at the same time, you could already return the regex object, which seems a simpler way to work than using string-based regexes:
function return_some_regex() {
return /^-?(?:(?!0\d)\d+\.?\d*)?$/;
}
console.log("0.123".match(return_some_regex()));
console.log("-03233".match(return_some_regex()));
console.log("333-3334".match(return_some_regex()));
You could match an optional hyphen, followed by either a floating point or match a number starting with 1-9
^-?(?:\d+\.\d+|[1-9]\d*|0\.?)$
The pattern will match
^ Start of string
-? Optional hyphen
(?: Non capture group
\d+\.\d+ Match 1+ digits, dot and 1+ digits
| Or
[1-9]\d* Match a digit 1-9 and 0+ digits 0-9
| Or
0\.? Match a zero and optional dot
) Close group
$ End of string
Regex demo
let pattern = /^-?(?:\d+\.\d+|[1-9]\d*|0\.?)$/;
["-0123",
"0123123",
"-03123123",
"1234",
"-0.234",
"0.4",
"0.3312312",
"1",
"-1234",
"0",
"0."
].forEach(s => console.log(`${s} match:${pattern.test(s)}`));
If you want to match an empty string or just a single hyphen, you can also make the second part optional.
^-?(?:\d+\.\d+|[1-9]\d*|0\.?)?$
Regex demo
I have following regex to validate numbers in input
var reg = /^\d+$/;
Now i want to allow ,(commas) and .(period) in number field as following will some one help me writing regex to allow following number format ?
10000000
10,000,000
10000000.00
You may use
/^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?$/
See the regex demo
If you only need to allow 2 digits after the decimal separator, replace (?:\.\d+)? with (?:\.\d{1,2})?.
Details:
^ - start of string
(?:\d{1,3}(?:,\d{3})*|\d+) - 2 alternatives:
\d{1,3}(?:,\d{3})+ - 1 to 3 digits and one or more sequences of a comma and 3 digits
\d+ - 1 or more digits
(?:\.\d+)? - an optional sequence of:
\. - a dot
\d+ - 1 or more digits
$
You could use
^((\d{1,2}(,\d{3})+)|(\d+)(\.\d{2})?)$
see Regex101
or
^((\d{1,2}(,\d{3})+)|(\d+))(\.\d{2})?$
if you want 10,000,000.00 to get matched to.
I have this regex which validates if a string is a decimal number.
Also this checks if it has at most 9 decimals after ".".
^[-]?[0-9]+([\.][0-9]{0,9})?$
I need to add another check, which limits the total number of digits.
Mention: I need the total number of digits to be less then 38, including the decimal after the point, thus I cannot add the range just to decimals before the point.
valid ex:
-12345678901234567890123456789.123456789
123456789012345678901234567890.1
-1.123456789
Use a negative lookahead:
^(?=(?:\D*\d){n}\D*$)[-]?[0-9]+(?:\.[0-9]{0,9})?$
^^^^^^^^^^^^^^^^^^^^
Where n is the limit argument for the amount of digits in the input string.
Example:
^(?=(?:\D*\d){7}\D*$)-?[0-9]+(?:\.[0-9]{0,9})?$
will match 1234.567, but will not match 1234.56 and 1234.5678.
See the regex demo
Now,
I need the total number of digits to be less then 38
Just use a negative lookahead:
^(?!(?:\D*\d){38})-?[0-9]+(?:\.[0-9]{0,9})?$
^^^^^^^^^^^^^^^^^
This (?!(?:\D*\d){38}) lookahead will fail the match if there are 38 (not obligatorily consecutive due to \D*) digits in the string.
Pattern explanation:
^ - start of string
(?!(?:\D*\d){38}) - the negative lookahead that will try to match 0+ non-digits (\D*) followed with a digit exactly 38 times and if it matches that text, no match will be returned
-? - an optional (1 or 0) hyphen (no need to place it into a character class as it is not a special regex metacharacter here)
[0-9]+ - 1+ digits (use \d instead to make it shorter)
(?:\.[0-9]{0,9})? - an optional (1 or 0 occurrences) sequence of:
\. - a literal dot
[0-9]{0,9} - 0 to 9 digits (again, \d{0,9} is shorter)
$ - end of string
And if you need to only check the integer part to have less than 38 digits, use
^(?!(?:[^\d.]*\d){38})[-]?[0-9]+(?:\.[0-9]{0,9})?$
See this regex demo
You can use regex with positive look ahead assertion /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/
$('input').on('input', function() {
$(this).css('color', /^-?(?=[.\d]{0,39}$)\d{0,38}(\.\d{1,9})?$/.test(this.value) ? 'green' : 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input>
Regex explanation
I have following regular expression: ^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)
It should not allow 4 digit number such as 4444. The expression is working fine if I try here, but in javascript, the code is not working as expected. It is allowing 4 digit numbers. All other validations work fine.
Here is my code:
http://jsfiddle.net/PAscG/
reg0str = "^-?([0-9]{0,3}$|[0-9]{0,2}\.?[0-9]{0,1}$)";
var reg0 = new RegExp(reg0Str);
if (reg0.test(temp)) return true;
UPDATE TO EXPLAIN Functionality:
I want to allow only 3 digits. So either I can allow only 1 digit after decimal and 2 before decimal or I can allow max of 3 digits before decimal and nothing after decimal.
So my first part:
[0-9]{0,3}$ I assume this should allow a max of 3 digits and only numbers.
Next part: [0-9]{0,2}\.?[0-9]{0,1}$ should allow max of 2 digits before decimal and a max of 1 digit after decimal.
Following OP's clarification
The regexp is
/^-?(\d{0,3}\.?|\d{0,2)\.\d)$/
^ start of string
-? optional minus sign (use [-+]? if you accept a plus sign)
( start of OR group
\d{0,3} 0 1, 2 or 3 digits
\.? optional decimal point
| OR
\d{0,2} 0 1, or 2 digits
\. decimal point
\d final decimal
) end of OR grouping
$ end of string
Try this:
var reg0str = "^\-?[0-9]{0,2}[\.]?[0-9]?$";
I'm not sure why, but the period seems to be being treated as the wildcard character if not encapsulated within a class.
Here's the updated jsfiddle
"…\.…" is a string literal - the backslash escapes the dot to a dot and the regex dot matches a digit. You would need to escape the backslash to pass a string with a backslash in the RegExp constructor:
new RegExp("^-?([0-9]{0,3}$|[0-9]{0,2}\\.?[0-9]{0,1}$)")
or you use a regex literal (simplified, but still matching the same):
/^-?\d{0,2}\.?\d?$/