C# Masked TextBox with 0 or decimals

1.8k views Asked by At

Users have a textbox where they have to either enter a 0 or a value from 0.0001 to 0.9999. What regex can I use here? I have looked at other examples but don't see anything like this one.

4

There are 4 answers

0
Alan Araya On

Try this one:

/(0)+(.)+([0-9])/g

Also see thing link that might helps you build you won expreession. http://regexr.com/

0
Peter On

Try this, it will do the work but I was not tested for all cases.

Regex _regex = new Regex("^[0]+(.[0-9]{1,4})?$");
if (input == "0" || _regex.IsMatch(input))
{
     //Match
}
else
{
     //Does not match
}

Note: input is a string, in your case Textbox.Text!

0
voytek On

This is ready to use KeyPress event handler of TextBox control. It will prevent any input, except numeric between 0.0001 and 0.9999:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        //Only one dot is possible
        if ((sender as TextBox).Text.Contains('.') && (e.KeyChar == '.')) e.Handled = true;

        //Only numeric keys are acceptable
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) e.Handled = true;

        //Only one zero in front is acceptable, next has to be dot
        if (((sender as TextBox).Text == "0") && (e.KeyChar == '0')) e.Handled = true;

        double value = 0;
        string inputValue = (sender as TextBox).Text + e.KeyChar;

        if ((sender as TextBox).Text.Length > 0)
        {
            //Just in case parse input text into double
            if (double.TryParse(inputValue, out value))
            {
                //Check if value is between 0.0001 and 0.9999
                if (value > 0.9999) e.Handled = true;
                if (((sender as TextBox).Text.Length > 4) && (value < 0.0001)) e.Handled = true;
            }
        }
        else if (e.KeyChar != '0')
        {
            e.Handled = true;
        }
    }
3
Oli On

I'd say this is quite an effective solution. It allows for any strings entered that is either just a '0' or strings with '0.' followed by up to 4 of any digit.

        Regex myRegex = new Regex("^(?:(?:0)|(?:0.[0-9]{1,4}))$");
        Console.WriteLine("Regex: " + myRegex + "\n\nEnter test input.");
        while (true)
        {
            string input = Console.ReadLine();
            if (myRegex.IsMatch(input))
            {
                Console.WriteLine(input + " is a match.");
            }
            else
            {
                Console.WriteLine(input + " isn't a match.");
            }
        }

Here's a list of tests...

enter image description here