I'm having a hard time coming up with the most suitable regex for my needs.
I want a regex that only validates numbers from 1-8, with or without a decimal point
1 // Valid
3 // Valid
8 // Valid
2.00 // Valid
4.45 // Valid
7.60 // Valid
9 // Invalid
10 // Invalid
9.00 // Invalid
50.40 // invalid
So far this is what I came up with, but ^([0-8]$\.?[0-8]*|\.[0-8]+) but this only accepts numbers from 1-8, and nothing with a decimal. Can someone kindly provide a suitable regex for this example?
I guess it would be better to limit regex to string parsing. My best approach would be to parse a valid number from the string and then convert it to number before doing any validation on its value as being < x
But if you really want to go via regex (and it will be hard to change in case) would be with something like:
^0*([0-7](\.\d+)?|8)$
It matches any number between 0 and 8 ... decimal point is allowed if followed by numbers and the highest valid number like that would be 7.999999999... followed by the next valid integer number being 8.
Trailing zeros are considered.
Related
I have a field, I have added a regex for it. So this regex does not allow more than 7 digits before decimal and more than two digits after the decimal. this is working fine, it gives an error message properly. Now I want to give different-2 messages for before decimal points and after decimal points. If the user enters more than 7 digits of a numeric value, then the error message will come under the field as “Maximum 7 digits are allowed.” If the user enters more than 2 digits of the decimal value, then the error message will come under field as “Maximum 2 digits of decimals are allowed.”
[RegularExpression("^\\d{0,7}(\\.\\d{0,2})?$", ErrorMessage = "Please enter Comment in the right format.")]
public decimal? decimalField { get; set; }
Edit:
Can we do something line like?
https://stackoverflow.com/a/4803634/13211840
If not possible in MVC then how is it possible using javascript or jquery?
I don't think so it's possible through data annotations. One approach could be, you explicitly validate your model and customize error message based on regex condition in your Action.
if (Regex.IsMatch("value", "regPattern"))
{
ModelState.AddModelError("FieldName", "ErrorMessage");
}
In your current pattern ^\\d{0,7}(\.\\d{0,2})?$ all parts are optional and will also match an empty string or a single dot as the decimal part accepts between 0 and 2 digits.
If you want to use 2 patterns for 2 different messages, you could match a pattern that allows 1-7 digits before the decimal and 1-2 digits after the dot.
If you want to allow a leading dot without a digit, you could use \\d{0,7} instead.
^\\d{1,7}(?:\\.\\d{1,2})?$
Regex demo
To match 1 to 7 digits:
^\\d{1,7}$
I want number in this format
(123)-456-7890
The maximum length assigned is 10.
The regular expression used to obtain the above format is:
if (onlyNums.length === 10) {
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');
If length>10 I want the above format for the number and to ignore the rest of the digits(right trim).
How can I do that?
If you remove the if condition and add a "catch-all" regex .* at the end, it will ignore whatever comes after the 10th digit:
const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4}).*/, '($1) -$2-$3');
This assumes that onlyNums actually contains nothing but digits (and at least 10 of them). Otherwise, the result might be unexpected.
Test it live on regex101.com.
I have a requirement to validate some inputs which should be in format ###.##
Invalid inputs are:
-11.10 ==> no negative
000.00 or 0 ==> 0 not allowed should be positive
Valid inputs are:
1
11
111
1.1
11.11
111.11
I have tried with the following regex ^([^-]\d{0,2}(.\d{1,2})?)$ which fulfills my requirements except it's accepting 0 which I don't want. How I can modify my regex so only 0's do not get matched?
Thanks For Help
Try
^(?=.*[1-9])\d{1,3}(?:\.\d\d?)?$
It should do it for you.
It starts with a positive look-ahead to make sure there's a digit other than 0 present.
Then it matches 1-3 digits, optionally followed by a . and 1-2 digits.
Your regex101 updated.
([0-9]){1,3}(\.[0-9]{1,2})? is the expression you are searching for.
([0-9]){1,3} = any number sequence with a length from 1 up to 3
(\.[0-9]{1,2})? = "?" maybe there is a float tail
(\.[0-9]{1,2}) = float tail must start with a dot and decimal numbers have to be up to 2
There is a way to except all zero sequences but it will waste your time for no reason, as you can simply check it with if myNum > 0.
It will work for negative values also, but this regex excludes them too.
^[1-9][0-9]*(\.[0-9]+)?$|^0\.[0-9]+$
This will work for you. It accepts all valid positive decimal numbers excluding 0.
I need regex to validate a number that could contain thousand separators or decimals using javascript.
Max value being 9,999,999.99
Min value 0.01
Other valid values:
11,111
11.1
1,111.11
INVALID values:
1111
1111,11
,111
111,
I've searched all over with no joy.
/^\d{1,3}(,\d{3})*(\.\d+)?$/
About the minimum and maximum values... Well, I wouldn't do it with a regex, but you can add lookaheads at the beginning:
/^(?!0+\.00)(?=.{1,9}(\.|$))\d{1,3}(,\d{3})*(\.\d+)?$/
Note: this allows 0,999.00, so you may want to change it to:
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
which would not allow a leading 0.
Edit:
Tests: http://jsfiddle.net/pKsYq/2/
((\d){1,3})+([,][\d]{3})*([.](\d)*)?
It worked on a few, but I'm still learning regex as well.
The logic should be 1-3 digits 0-1 times, 1 comma followed by 3 digits any number of times, and a single . followed by any number of digits 0-1 times
First, I want to point out that if you own the form the data is coming from, the best way to restrict the input is to use the proper form elements (aka, number field)
<input type="number" name="size" min="0.01" max="9,999,999.99" step="0.01">
Whether "," can be entered will be based on the browser, but the browser will always give you the value as an actual number. (Remember that all form data must be validated/sanitized server side as well. Never trust the client)
Second, I'd like to expand on the other answers to a more robust (platform independent)/modifiable regex.
You should surround the regex with ^ and $ to make sure you are matching against the whole number, not just a subset of it. ex ^<my_regex>$
The right side of the decimal is optional, so we can put it in an optional group (<regex>)?
Matching a literal period and than any chain of numbers is simply \.\d+
If you want to insist the last number after the decimal isn't a 0, you can use [1-9] for "a non-zero number" so \.\d+[1-9]
For the left side of the decimal, the leading number will be non-zero, or the number is zero. So ([1-9]<rest-of-number-regex>|0)
The first group of numbers will be 1-3 digits so [1-9]\d{0,2}
After that, we have to add digits in 3s so (,\d{3})*
Remember ? means optional, so to make the , optional is just (,?\d{3})*
Putting it all together
^([1-9]\d{0,2}(,?\d{3})*|0)(\.\d+[1-9])?$
Tezra's formula fails for '1.' or '1.0'. For my purposes, I allow leading and trailing zeros, as well as a leading + or - sign, like so:
^[-+]?((\d{1,3}(,\d{3})*)|(\d*))(\.|\.\d*)?$
In a recent project we needed to alter this version in order to meet international requirements.
This is what we used: ^-?(\d{1,3}(?<tt>\.|\,| ))((\d{3}\k<tt>)*(\d{3}(?!\k<tt>)[\.|\,]))?\d*$
Creating a named group (?<tt>\.|\,| ) allowed us to use the negative look ahead (?!\k<tt>)[\.|\,]) later to ensure the thousands separator and the decimal point are in fact different.
I have used below regrex for following retrictions -
^(?!0|\.00)[0-9]+(,\d{3})*(.[0-9]{0,2})$
Not allow 0 and .00.
','(thousand seperator) after 3 digits.
'.' (decimal upto 2 decimal places).
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.