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}$
Related
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.
I need an expression to validate numbers between 1.0 to 4.5 but it's not working precisely for it.
Expression I'm using: /^[1-4]{0,1}(?:[.]\d{1,2})?$/
Requirement is to only accept value between 1.0 to 4.5
but
buildInserForm(): void {
this.insertLeavesForm = this.fb.group({
**your text**
hours: [
{ value: 4.5, disabled: true },
[
Validators.required,
Validators.pattern(**/^[1-4]{0,1}(?:[.]\d{1,2})?$/**),
],
],
});
}
Currently restricting the numbers from 1.0 to 4.0, But the issue comes in decimal points, it shows an error if entered any number between 6-9 in decimal places, like 1.7,2.8, 3.9.
acceptance criteria are 1.0 to 4.5.
This image shows that value is getting entered to multiple decimal places which is wrong,
Only single decimal place value is required.
Regex are pretty bad to check number ranges. Should it consider non decimal numbers? What if there is more than one decimal point? What if you should ever want to increase/decrease range? Here's more on the topic: Regular expression Range with decimal 0.1 - 7.0
I would suggest simple min/max Validators. Plus this would also let you control if user value is below or above criteria, letting you to display custom error messages appropriately, for example. Whereas regex will simply evaluate to true/false.
[
Validators.required,
Validators.min(1),
Validators.max(4.5),
Validators.maxLength(3)
]
You may use the following regex pattern:
^(?:[1-3](?:\.\d{1,2})?|4(?:\.(?:[0-4][0-9]|50?)?))$
Demo
This regex pattern says to match:
^ start of the input
(?:
[1-3] match 1-3
(?:\.\d{1,2})? followed by optional decimal and 1 or 2 digits
| OR
4 match 4
(?:
\. decimal point
(?:[0-4][0-9]|50?)? match 4.00 to 4.49 or 4.5 or 4.50
)
)
$ end of the input
This is a regex that I created.
pattern(/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/)
Explaination
/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/
/^ start of the input
[1-3] First input to be taken between
{0,1} This shows how many times it can be repeated
( Parenthesis shows next entered digit is optional
? Question mark is for using digit zero or once
:[.] This is for what the next Character would be eg ".", "#"
[0-9] input to be taken between.
{0,1} This shows how many times it can be repeated.
) Option part closes
? Question mark is for using digit zero or once.
[4] This shows what can be other input that can be taken
{0,1} How many times it can be use , SO in this case 0 or 1 times
(?:[.] There after again same option part with decimal point
decimal value of 4and its limitation for 0 to 5
[0-5] This is to set limitation 0-5 as per our requirement
{0,1} Its existence 0 or 1 times
) Close of optional part.
? Thereafter showing the existence of an optional part once or twice.
$/ Shows to match expression after it.
I'm facing a problem.
I want to validate Bangla int and float numbers using RegEx.
I am using the following RegEx
([০-৯][০-৯]*$)
But it's not working on ২৬৭
And again, How I would implement floating bangla numbers (For example:৬৭.৫৬) supported regex once which will select int and float Bangla Numbers. Please somebody help me. (It's for my learning purposes only)
You may use the following to match simple integer or float Bengali numbers:
/[০-৯]+(?:\.[০-৯]+)?/
/[\u09E6-\u09EF]+(?:\.[\u09E6-\u09EF]+)?/
You may validate them (the whole string should match) with
/^[০-৯]+(?:\.[০-৯]+)?$/
/^[\u09E6-\u09EF]+(?:\.[\u09E6-\u09EF]+)?$/
See the regex demo.
Details:
^ - start of string
[\u09E6-\u09EF]+ - one or more Bengali digits
(?:\.[\u09E6-\u09EF]+)? - an optional occurrence of a . and one or more Bengali digits
$ - end of string.
Try this:
regex = /[০-৯]+(\.[০-৯]*)?$/
console.log(regex.test("২৬৭"))
Maybe that was a little bit confusing. Let's break the regex /[০-৯]+(\.[০-৯]*)?$/ down.
First part - `[০-৯]+`
This means that it will match 0-9, one or greater number of times.
Second part - `\.[০-৯]*`
This means that it will match a decimal point ., along with zero or greater numbers.
Third part - `(\.[০-৯]*)?`
The brackets just mean that you are grouping it. The question mark makes it optional.
Fourth part - `$`
Matches to the end of the string.
Putting that together and summarizing: First it matches for a string of numbers. After it encounters a non-number, it checks if it is a decimal point. If it is, then it matches the decimal, and however many numbers come after it (which might be none, meaning that the decimal is there for significant figure purposes, or for another reason).
I'm looking for a regular expression in javascript that takes care of this:
Accept only numbers between 6 and 15 digits, 6 is the minimum.
Numbers cannot contain groups of repeated digits, such as 408408 or 123123
Numbers cannot contain only two different digits, such as 121212
I started with this, then I was loss
^[0-9]{6,15}$
Instead of just a Regex, use a combination of if-statements and a RegEx.
function validateNumber() {
var numbers = document.getElementById('numbers1').value;
if (numbers && !isNaN(numbers)) {
// make sure a that something was entered and that it is a number
if (numbers.length < 6 || numbers.length > 15) {
// make sure number is between 6 and 15 digits
alert('Number must be between 6 and 15 digits long.');
} else if (numbers.match(/(.+)\1+/)) {
// make sure that the numbers contain no repeated digits
alert('Number cannot be repeated.');
} else {
alert('Number validated!');
// otherwise, the number is validated
}
} else {
// if no number was entered
alert('Please enter a number.');
}
}
<input type="text" placeholder="enter numbers" id="numbers1" />
<input type="button" value="Validate!" onclick="validateNumber()" />
You have the first rule correct:
^\d{6,15}$
That covers both the 6-15 length requirement and the fact that it has to be numeric.
With the next rule, it's easier to test for repeated substrings than to test for their absence:
(.+)\1
The last one is a lot more complicated. Here's how you test for at least 3 distinct characters:
(.+)(?!\1)(.+)(?!\1|\2).
Put it all together and what do you get:
^(?=\d{6,15}$)(?!.*(.+)\1)(.+)(?!\2)(.+)(?!\2|\3).+$
That answers your question as written, but as I said in the comments, you should consider very carefully whether you're starting from the right assumptions. You don't have to use regex for this, nor do you have to do it all in one regex. Will the pattern above be easy for you to work with when you come back in 6 months and have to change the rules?
More importantly, if you're trying to make sure users pick a strong password, the rules you're using will weaken your security by reducing the number of possible choices. And the maximum length of 15 characters suggests you're storing passwords in plain text. You should be hashing them.
Here's my attempt, just for the challenge:
^(?!\d*?(\d+?)\1)\d{6,15}$
Demo
The (?!\d*?(\d+?)\1) part will make sure there are no groups of repeated digits by matching a group of digits and trying to match the same digits immediately after. If it finds one, the match fails.
If you want to allow two same consecutive digits, replace (?!\d*?(\d+?)\1) with (?!\d*?(\d{2,}?)\1)(?!(\d)\2*(\d)(?:\2|\3)*$). This will then make sure there are more than 2 different digits by matching a series of one digit, then a different digit followed by a series of a combination of both digits. If it reaches the end of the string it forces the match to fail.
But it'll be probably more maintainable to just do it the conventional way, without regex.
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).