开发者

Validating input for Textbox on C# Winforms

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

The 开发者_如何学Cpattern 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜