Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
i have an text box which accepts numeric and decimal values.The text box allows only one digit after the decimal point.Max length of text box is 4.

now when the text box contains a text as ".8", how can i restrict user from entering digits after a decimal point(i.e when cursor position is immediately after the decimal point).

At the same time i should allow max of two digits before the decimal point

ex:
1.2---?valid
12.3---->valid
.78--->invalid
.768--->invalid

So how can i set the cursor position so that it will allow user to enter max of two digits before the decimal point and restrict user from entering digits after the decimal point when there is already a single digit after the decimal point(like ".8").
Posted

1 solution

You can use Regex to detect input discrepancy, adapt from this example:
C#
using System;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        string input = "12.3";

        Regex regex = new Regex(
             "^\\d{0,2}[.]\\d$",
             RegexOptions.IgnoreCase
            | RegexOptions.CultureInvariant
            | RegexOptions.Compiled
        );

   if (regex.IsMatch(input))
      {
          // do something
          Console.WriteLine("Valid");
      }
        else
        {
            // do other thing
            Console.WriteLine("Not valid!");
        }
    }
}
 
Share this answer
 
v2
Comments
Member 10593922 18-Mar-14 3:30am    
thank u for the reply

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900