Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating input for Textbox on C# Winforms

Tags:

c#

regex

winforms

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.

like image 272
BENBUN Coder Avatar asked Apr 22 '26 00:04

BENBUN Coder


2 Answers

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.

like image 200
cristobalito Avatar answered Apr 23 '26 15:04

cristobalito


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.

like image 23
Alex Zylman Avatar answered Apr 23 '26 15:04

Alex Zylman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!