Click here to Skip to main content
15,885,705 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everyone
How can i Make a textbox that accepts at first 4 letters and after that 7 digits otherwise give the user an error

i have no idea what to do please put me on the right direction

What I have tried:

i tried to use masked textbox but it didn't work

if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
Posted
Updated 2-Jan-18 23:38pm
v4
Comments
Samuel Corpuz 3-Jan-18 20:01pm    
Use ^[a-zA-Z]{4}\d{7}$ this. to Maximize the Shorter code

if (txtContainerNo.TextLength < 4)
         {
             e.Handled = !(char.IsUpper(e.KeyChar) || e.KeyChar == (char)Keys.Back);


         }

         else
         {
             e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
         }
 
Share this answer
 
if ((e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z) || (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9))
       {
           charCount++;
       }


       else if (e.KeyCode == Keys.Back)
       {
           charCount--;
       }

       else
       {

       }




       if (charCount <= 4)
       {
           if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z && e.Shift && e.KeyCode == Keys.Back)
           {



           }
           else
           {
               e.SuppressKeyPress = true;
           }

       }


       else if (charCount > 4)
       {
           if (!(e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z && e.KeyCode != Keys.Back))
           {



           }
           else
           {
               e.SuppressKeyPress = true;
           }
 
Share this answer
 
v3
Your regex only works for digits, and doesn't care how many there are ,provided there is at least one somewhere in the string.
Try this:
^[a-zA-Z]{4}\d{7}$
 
Share this answer
 
Comments
Member 13077860 3-Jan-18 9:27am    
Finally i found the solution

if (txtContainerNo.TextLength < 4)
{
e.Handled = !(char.IsUpper(e.KeyChar) || e.KeyChar == (char)Keys.Back);


}

else
{
e.Handled = !(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}
OriginalGriff 3-Jan-18 10:01am    
So... I type "ABCD", the use the mouse to click in the middle and type "1234567" you will allow "AB1234567CD" through?

Don't do "while you type" validation: it only confuses the user. Use the regex I gave you in the Validating event.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900