PineappleLord PineappleLord - 1 month ago 23
C# Question

post code validation c#

I'm writing an if statement to validate a post code entry. You will find the code below. I want the program only to allow entries in

AB123
or
A123
format. I'm not really sure how to go about this, I already have a keypress event that only allows them to type alphanumeric characters, but I also want this to only allow them to progress with a valid post code. Any help would be great thanks.

if (string.IsNullOrWhiteSpace(TXTPostCode.Text))
{
MessageBox.Show("Please enter a value for PostCode!");
}
else
{
string postCode = Convert.ToString(TXTPostCode.Text);
if ()//postCode not in AB123 or A123 format
{
MessageBox.Show("PostCode needs to be in AB123 or A123 format!");
}
else
{
fm.SavePostCode(Convert.ToString(TXTPostCode.Text));
}
}

Answer

I suggest using regular expressions in order to check if user input matches the pattern:

   using System.Text.RegularExpressions;

   ...

   if (Regex.IsMatch(TXTPostCode.Text, "^[A-Z]{1,2}[0-9]{3}$")) 
     fm.SavePostCode(TXTPostCode.Text);
   else 
     MessageBox.Show("PostCode needs to be in AB123 or A123 format!");
Comments