简体   繁体   中英

C# Masked TextBox with 0 or decimals

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.

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...

在此处输入图片说明

Try this one:

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

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

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!

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM