zaw latt
zaw latt

Reputation: 1

Validate Textbox was specified fomat

How do I validate Textbox input in the following format? The format is:

"123dg-erf53-f5d5s-55dh5-gs45j"

Upvotes: 0

Views: 624

Answers (3)

Pavel Donchev
Pavel Donchev

Reputation: 1889

Using Otiels regex, you can do something like:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        string regex = "(([0-9a-zA-Z]){5}-){4}([0-9a-zA-Z]){5}";

        this.textBox1.BackColor = Regex.IsMatch(this.textBox1.Text, regex) && !textBox1.Text == string.Empty ?
                            System.Drawing.Color.Green :
                            System.Drawing.Color.Red;
        if (this.textBox1.Text == string.Empty)
        {
            this.textBox1.BackColor = System.Drawing.Color.White;
        }
        else
        {
            this.textBox1.ForeColor = System.Drawing.Color.White;
        }
    }

In the TextBox_TextChanged handler (my TextBox name is textBox1). This can be easilly added to a custom control - you inherit from TextBox, attach to the TextChanged event and replace the textBox1 code bellow with this.

This way you can re-use the control. You may also add a property such as public string ValidationRegex { get; set; } so you can pass different regular expressions and be able to validate anything, not just license keys.

The MaskedTextBox is a valid option as well, depending what exactly do you need to achieve.

Update: the regex above will match a string that contains of 5 groups, each with 5 characters which can be letter (upper or lower case) or a number. Since there was a comment on that, the regex should be modified to accomodate groups with different number of characters. Here it is:

    string regex = "[0-9a-zA-Z]{6}-[0-9a-zA-Z]{5}-[0-9a-zA-Z]{5}-[0-9a-zA-Z]{5}-[0-9a-zA-Z]{6}";

This regex (although being a lot longer than the one Otiels came up with) will allow you to control the number of characters in each group. Just replace it in the code above and it should work for a string that has a group of 6 characters, followed by two groups of 5 characters, followed by a group of 6 characters. By the way this was going to be my initial proposal (except that in the original answer I was having 5 in each of the quantifiers), but I really favored Otiels solution as being a lot more elegant for the initial task than mine.

Upvotes: 0

Otiel
Otiel

Reputation: 18743

Here's a regex to validate it:

"(([0-9a-zA-Z]){5}-){4}([0-9a-zA-Z]){5}"

Upvotes: 0

Svarog
Svarog

Reputation: 2208

You can either use MaskedTextBox , or if it's functionality is not enough, create a handler to it's TextChanged event, and use a regex to validate the text.

Upvotes: 1

Related Questions