Regex Decimal Validation in C# Java
Regex is very usable expression notation which is approximately same for all Programming Languages (like Java , C#, Python, JavaScript etc ) and also it is Very fast as compare to if else Logic.
I already share how to use Regex in Programming Langues C#.
So, Regular expression (regex) for Decimal Point Validation is following
^([0-9]{1,5}(\\.[0-9]{0,2})?)()*$
and We can use this Expression in Our Code like Java.
String abc="10.0";
if(abc.matches("^([0-9]{1,5}(\\.[0-9]{0,2})?)()*$"))
{
System.out.println("VALIID");
}
else
{
System.out.println("INVALIID");
}
Let us understand what this pattern checks. The first part matches one or more digits, like 0, 25 or 1234. After that, the decimal part is optional: a dot followed by one or more digits, for example the .5 in 12.5. Because this decimal part is placed inside an optional group, both whole numbers and decimal numbers pass the validation.
Remember that this is only format validation. It tells you the text looks like a decimal number; it does not check any range, such as a minimum or maximum allowed value. The pattern given here also does not allow a minus sign, so negative numbers will fail the test. And in many countries the decimal separator is a comma, not a dot, so if your users type 12,5 this pattern will reject it. For real applications, combine this check with parsing the value in code before you save it.

Comments
Post a Comment