TESTEVERYTHING

Thursday 4 March 2021

How to validate NUMBERS with a regular expression?

 It depends. What type of number? What precision? What length? What do you want as a decimal separator? Etc. The following examples should help you want with the most common tasks.

Positive integers of undefined length:
^\d+$
Positive integers of maximum length (10 in our example):
^\d{1,10}$
Positive integers of fixed length (5 in our example):
^\d{5}$
Negative integers of undefined length:
^-\d+$
Negative integers of maximum length (10 in our example):
^-\d{1,10}$
Negative integers of fixed length (5 in our example):
^-\d{5}$
Integers of undefined length:
^-?\d+$
Integers of maximum length (10 in our example):
^-?\d{1,10}$
Integers of fixed length (5 in our example):
^-?\d{5}$
Numbers of undefined length with or without decimals (1234.1234):
^-?\d*\.{0,1}\d+$
Numbers with 2 decimals (.00):
^-?\d*\.\d{2}$
Currency numbers with optional dollar sign and thousand separators and optional 2 decimals ($1,000,00.00, 10000.12, 0.00):
^$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\($?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$
Percentage from 0 to 100 with optional 2 decimals and optional % sign at the end (0, 0.00, 100.00, 100%, 99.99%):
^-?[0-9]{0,2}(\.[0-9]{1,2})?%?$|^-?(100)(\.[0]{1,2})?%?$

No comments:

Post a Comment

Which one is right ?

Translate







Tweet