开发者

I need to make sure that texbox only accepts this specific format. how do i do that?

Acceptable format putting in textbox : 00-00-mach-0-00

Where, from the left:


You could create a regular expression that represents the rules you are trying to enforce and check whether the input matches whenever the Validating-event fires.


I would use a MaskedTextBox control. In the properties box for the control, click on Mask and set the Mask Description to Custom. This mask should work for you: "00-00-m\ach-0-00" You would probably need to add additional validity checks afterwords using the split method above. But it should save you some additional coding.


I would do several things in such a case:

  1. Sample I would put a sample / demo format as a label or text for the user so that they can see what I want them to enter. I would not put a tooltip because it is annoying and they have to do something (mouseover) to get the tip. I would put it where it is visible.
    • Regex validations Add a regex validation in the VALIDATE event to ensure that the data is valid (just 0, 1, 2, 3 and not 4 through 9; etc)
    • Input Mask Using an input mask would help the users to enter the data in the format that is required.
    • If you do not want input masks and want to allow freeform text, then the regex comes in even more handy for you to validate the data. Once validated, you can format it in the actual form you want and display it back on the VALIDATE event.


You'll need to split the input. One approach is to use String.Split with a - as the split character.

string input[] = inputString.Split('-');

You can then check that you've got 5 sub strings:

if (input.Length != 5)
{
    // Incorrect format
}

And then check each sub strings for the correct format. For example to check that the 4th sub strings is a digit and either 1, 2, 3 or 4:

int number;
if (Int32.TryParse(input[3], out number))
{
    if (number < 1 || number > 4)
    {
        // Incorrect format
    }
}

Do this when the text box loses focus.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜