3

I need to validate the decimal datatype in the incoming feed. Integer part and the fraction value combined together can have up to 7 chars. Fraction value is optional. Leading + or - is also optional.

For example DECIMAL(7, 2) defines numbers of the form 12345.67

test case

Valid
-1
+1
1
+.1
-.1
.1
+11111.11
-11111.11
11.11
11111

Invalid
1111111
11.11111
0.111111
.1111111
+111111.11
-111111.11
+11111.111
-11111.111
11111.111
111111.11
+1.
-1.
1. 

This is what I currently use

[+-]?\d\.?\d?

How should I change this?

1 Answer 1

5

You can use this regex:

/^[+-]?\d{0,5}(?:\.\d{1,2})?$/gm

RegEx Demo

Sign up to request clarification or add additional context in comments.

4 Comments

I've added explanation of lookahead used in answer.
Sorry @anubhava I made a blunder. I have edited the test cases.
DECIMAL(7, 2) defines numbers of the form 12345.67, so the fraction part is given 2 chars and the rest 5 chars go to integer.
Cool, so (?=(?:\D*\d){1,7}$) has any relevance in the new snippet, I feel it is redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.