Now I am trying to check for correct format in this ID number entered by the user in this program. Now I am aware of the match case, but I'm trying to avoid doing that. I was considering a foreach loop, but the ID is in XX-9999 format and I don't know how to check different data types in that kind of loop.
I tried to use a for loop because my thinking was since a string is just an array of characters, that I can treat it as such. But I think that my index is being checked instead of the string characters.
Either way, here is my method:
public bool Validate_Employee_ID()
{
const int VALID_LENGTH = 7; // Length of a valid string
bool valid = true; // Flag to indicate validity
string strEmployeeID = txtEmployeeID.Text.Trim(); // get trimmed string from txtEmployeeID
string[] stringEmpIDSplit = strEmployeeID.Split('-');
if (strEmployeeID.Length == VALID_LENGTH)
{
// Check the first two characters in string.
for (int i = 0; i <= strEmployeeID[1]; i++)
{
// if the character is not a letter, valid equals false
if (!char.IsLetter(strEmployeeID[i]) == true)
{
MessageBox.Show("1) The employee ID must be in the following format: XX-9999.", "Entry Check", MessageBoxButton.OK, MessageBoxImage.Information);
txtEmployeeID.Focus();
// first two chars are not letters
valid = false;
return valid;
}
}
// Check the rest of the string to check the format.
for (int j = strEmployeeID[3]; j <= strEmployeeID[6]; j++)
{
// if the character is not a letter, valid equals false
if (!char.IsDigit(strEmployeeID[j]) == true)
{
MessageBox.Show("2) The employee ID must be in the following format: XX-9999.", "Entry Check", MessageBoxButton.OK, MessageBoxImage.Information);
txtEmployeeID.Focus();
// last 4 chars are not numbers
valid = false;
return valid;
}
}
}
else valid = true;
return valid;
}
^[A-Z]{2}-[0-9]{4}$- if you need additional characters you can add them to the match groups