1

I am having trouble with a decimal regex that needs to allow positive or negative numbers and up to 8 decimals.

Here is what I have.

^-?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]{1,9})?|\.[0-9]{1,9})$ 

For the most part, this works, but it does not validate .00000001 and I cannot figure out why. It doesnt seem to work for any decimal where I have more than 6 zeros i a row.

export class AmountValidateDirective implements Validator { validate(c: FormControl): any { let amount = c.value; const isValid = /^-?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]{1,9})?|\.[0-9]{1,9})$/.test(amount); const message = { 'amountValidate': { 'message': 'Must be Decimal with less than 8 digits' } }; return isValid ? null : message; } }

1

2 Answers 2

3

Try this regex:

^[+-]?\d*\.\d{1,8}$ 

Click for Demo

Explanation:

  • ^ - asserts the start of the line
  • [+-]? - matches either + or -, optionally
  • \d* - matches 0+ occurrences of a digit. This represent the digits before the decimal part.
  • \. - matches the decimal point .
  • \d{1,8} - matches a minimum of 1 digit and a maximum of 8 digits
  • $ - asserts the end of the line
Sign up to request clarification or add additional context in comments.

1 Comment

nice+1! way easier than what he has currently ;-)
2

First of all, your current regex accept up to 9 decimals. I have adapted it to have maximum 8 digits after the dot.

^-?(?:(?:0|[1-9][0-9]*)(?:.[0-9]{1,8})?|.[0-9]{1,8})$ ^ ^ ^ ^ 

I have tested it here and you can see the list of matches: https://regex101.com/r/SQYgq9/1/

1 1234 1234.1234 123456.123456 1234567.1234657 12345678.12345678 12345678.1243546788 <NOT MATCHED .91 0.12 .00001 .000001 .00000001 .000000001 <NOT MATCHED .000000000 <NOT MATCHED .0000000001 <NOT MATCHED -1 -1234 -1234.1234 -123456.123456 -1234567.1234657 -12345678.12345678 -12345678.1243546788 <NOT MATCHED -.91 -0.12 -.00001 -.000001 -.00000001 -.000000001 <NOT MATCHED -.0000000001 <NOT MATCHED 

If you still have issues for the input validation, you might have other problems like input not trimmed for example... From a regex point of view it is fine.

1 Comment

Sorry, I copied and pasted 9 digits as I was playing with this. It looks like when I use a small number, if I do a console.log() on my value, it's turning into "1e-8". I'm wondering if this is the value it's looking at when I do the regex test. I'm not sure how to stop this from happening in Angular/Typescript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.