Many times we need to validate user input for numeric, alphabetic and alphanumeric format. Windows forms do not have Maskedit box as in VB6. In this code sample we will see how to create your own custom control that inherits from the standard TextBox control and extends its functionality to validate numbers, alphabets and alphanumeric characters.
The Basic requirements for the control are to
- Allow numbers, alphabets and alphanumeric characters. The input can filtered based on the setting of "ValueType" property.
- In case the "ValueType" property is set to "Num" - Allow entry for one decimal point only, Allow a minus sign, but only at the first position in the text box, Allow numbers in the range between "MinValue" and "MaxValue", if they are set.
- Can make the field Mandatory. Can make the field Mandatory by setting property, default is False.
The value type property is an enumeration (ValMode) with following values:
- ValueType = AlphaNum, for Alphabet and Numerics
- ValueType = Num, for only Numerics
- ValueType = Alpha, for only Alphabet
We can have customized error message set via ErrorMessage property if this validation fails.
Checking for valid entry
The User input is validated/checked using the "KeyPress" event of the standard TextBox Control. The type of value (input) in the control is filtered using the Pre-defined value, which are provided by the Enumerator (Enum) "ValMode".
Changing focus color
Some times we have number of TextBox controls on the Win Form, and at times we can't find where the focus is, so we have added two properties which changes the color of the control when it receive and leave the focus. It is done by using the "Enter" and "Leave" events of the TextBox.