我正在进行一项课程作业,让我们为茶叶公司编写订购申请。分配要求我们验证用户输入。
我正在使用屏蔽文本框控件来显示州名缩写,电话号码和ZIP + 4代码。我为掩码中的状态缩写指定了LL(BTW,我想验证使用(原谅我)“如果字符串是AK || AL ||等”检查是否可行),所以没有办法输入任何东西但是字母。但是,对于邮政编码,我必须在我的文本框中固定为五位数,因为尝试将字段解析为int总是失败(我认为是因为连字符)。我的电话号码也有类似的问题。
所以,我的问题是:
当掩码本身包含(,)和 - ?时,如何验证掩码文本框中的用户数据?这些字符似乎被包含在支票中,这不是我想要的。
另外,我不想要正则表达式解决方案。我们还没有涵盖课堂上的人,我想坚持我理解的事情。我们已经介绍了try / catch,tryparse和switch case,但这些都不适合这个问题。
代码:
private void CastAndValidateInput()
{
validInputBoolean = false;
if (vendorNameTextBox.Text.Trim() != string.Empty)
{
if (vendorContactTextBox.Text.Trim() != string.Empty)
{
if (streetAddressTextBox.Text.Trim() != string.Empty)
{
if (cityTextBox.Text.Trim() != string.Empty)
{
if (stateMaskedTextBox.Text.Trim() != string.Empty)
{
if (zipCodeMaskedTextBox.Text.Trim() != string.Empty)
{
try // this works... if I use 5-digit ZIP code
{
zipCodeAsInteger = int.Parse(zipCodeMaskedTextBox.Text);
try // this still does not work, presumably because of the mask's special characters
{
telephoneNumberAsInteger = UInt32.Parse(telephoneNumberMaskedTextBox.Text);
try
{
quantityInteger = int.Parse(quantityTextBox.Text);
validInputBoolean = true;
}
catch
{
MessageBox.Show("You must enter a quantity as a whole number.", "INVALID QUANTITY ENTERED", MessageBoxButtons.OK);
quantityTextBox.Focus();
quantityTextBox.SelectAll();
}
}
catch
{
MessageBox.Show("This does not appear to be a valid telelphone number. Please enter only digits, and do not use separators such as (, ), or -.", "INVALID TELEPHONE NUMBER", MessageBoxButtons.OK);
telephoneNumberMaskedTextBox.Focus();
telephoneNumberMaskedTextBox.SelectAll();
}
}
catch
{
MessageBox.Show("You have entered an invalid value as a ZIP code. Please re-enter your ZIP+4 code in the indicated entry field.", "INVALID ZIP CODE", MessageBoxButtons.OK);
zipCodeMaskedTextBox.Focus();
zipCodeMaskedTextBox.SelectAll();
}
}
else // the format for the mask is 00000-9999 but the hyphen seems to be a problem for the checks I know how to do
{
MessageBox.Show("You must enter a ZIP+4 code.", "ZIP+4 NOT ENTERED", MessageBoxButtons.OK);
zipCodeMaskedTextBox.Focus();
}
}
else // this can be validated with a simple 'string equal to this || this || this' statement (right??)
{
MessageBox.Show("You must enter a state abbreviation.", "STATE ABBREVIATION NOT ENTERED", MessageBoxButtons.OK);
stateMaskedTextBox.Focus();
}
}
else
{
MessageBox.Show("You must enter a city.", "CITY NOT ENTERED", MessageBoxButtons.OK);
cityTextBox.Focus();
}
}
else
{
MessageBox.Show("You must enter a street address.", "STREET ADDRESS NOT ENTERED", MessageBoxButtons.OK);
streetAddressTextBox.Focus();
}
}
else
{
MessageBox.Show("You must enter a vendor contact name.", "VENDOR CONTACT NAME NOT ENTERED", MessageBoxButtons.OK);
vendorContactTextBox.Focus();
}
}
else
{
MessageBox.Show("You must enter a vendor name.", "VENDOR NAME NOT ENTERED", MessageBoxButtons.OK);
vendorNameTextBox.Focus();
}
}