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?)?))$
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.