tags:

views:

56

answers:

3

I am attempting to validate that the input into a textbox on a C# winforms conforms to a valid pattern.

The pattern must be a string that consists only of the following characters

  • 0 to 9
  • A to Z
  • "-"
  • "/"

I am looking at using the "Validating" event on the textbox to perform the validation but I am struggling with the correct Regular Expression to use - or maybe there's a better way than using a Regular Expression.

+2  A: 

The regex "[A-Z0-9_/]" should do it. Regex's seem like the most obvious choice here (it's a very simple validation), as long as you're happy using them.

You may need to quote some of the special characters with '\' depending on your language of choice. If you'd also like lower case letters to be allowed, then it'd be "[a-zA-Z0-9_/]".

Alternatively, something like "(\w?\d?_?/?)+" might work - the \w matches any character, \d any digit. The '?' matches the previous char 0 or 1 time while the + at the end allows multiple of these matches.

cristobalito
+1  A: 

You could use a KeyDown event on the TextBox and set the SuppressKeyPress field of the KeyEventArgs to true if it's not one of the characters you want to accept. You can check which character was entered by checking the KeyCode field of the KeyEventArgs. This will make it so that if a user tries to type a character that's not one of the ones you want, nothing will happen.

Alex Zylman
I've done it this way before as well - relatively straight forward. Be sure to handle special cases, e.g. where the user enters the numeric code for a character.
cristobalito
A: 

You don't need to validate it. Just use a MaskedTextBox

Bennor McCarthy