我正在尝试验证输入并处理此程序中的异常。验证以下内容:txtNAME中的字符串不应留空,txtTELEPHONE中的电话号码应至少为10位,而txtEMAIL应为电子邮件格式,并带有“@”和“。”。如何输入错误的输入,我如何验证这些输入并处理异常?
public partial class Form1 : Form
{
static int maxCount = 10;
int[] employeeID = new int[maxCount];
string[] employeeName = new string[maxCount];
string[] jobTitle = new string[maxCount];
string[] address = new string[maxCount];
int[] telephoneNumber = new int[maxCount];
string[] email = new string[maxCount];
int addCount = 0;
string fn = "employees.xml";
int currentRec;
private void btnADD_Click(object sender, EventArgs e)
{
employeeID[addCount] = Convert.ToInt32(txtEI.Text);
employeeName[addCount] = txtNAME.Text;
jobTitle[addCount] = txtJOB.Text;
address[addCount] = txtADDRESS.Text;
telephoneNumber[addCount] = Convert.ToInt32(txtTELEPHONE.Text);
email[addCount] = txtEMAIL.Text;
addCount++;
}
private void btnSAVE_Click(object sender, EventArgs e)
{
XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
w.Formatting = Formatting.Indented;
w.WriteStartDocument();
w.WriteStartElement("employees");
for (int i = 0; i < addCount; i++)
{
w.WriteStartElement("employees");
w.WriteElementString("employeeID", employeeID[i].ToString());
w.WriteElementString("employeeName", employeeName[i]);
w.WriteElementString("jobTitle", jobTitle[i]);
w.WriteElementString("address", address[i]);
w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
w.WriteElementString("email", email[i]);
w.WriteEndElement();
} w.WriteEndElement();
w.WriteEndDocument();
w.Close();
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
if (File.Exists(fn))
{
XmlTextReader r = new XmlTextReader(fn);
r.WhitespaceHandling = WhitespaceHandling.None;
while (r.Name != "employees")
r.Read();
while (r.Name == "employees")
{
r.ReadStartElement("employees");
employeeID[addCount] = Convert.ToInt32(r.ReadElementString("employeeID"));
employeeName[addCount] = r.ReadElementString("employeeName");
jobTitle[addCount] = r.ReadElementString("jobTitle");
address[addCount] = r.ReadElementString("address");
telephoneNumber[addCount] = Convert.ToInt32(r.ReadElementString("telephoneNumber"));
email[addCount] = r.ReadElementString("email");
r.ReadEndElement();
addCount++;
} r.Close();
DisplayRec();
}
}
private void DisplayRec()
{
txtEI.Text = employeeID[currentRec].ToString();
txtNAME.Text = employeeName[currentRec];
txtJOB.Text = jobTitle[currentRec];
txtADDRESS.Text = address[currentRec];
txtTELEPHONE.Text = telephoneNumber[currentRec].ToString();
txtEMAIL.Text = email[currentRec];
lblRECORD.Text = (currentRec + 1).ToString() + "/" + addCount.ToString();
}
private void btnBACK_Click(object sender, EventArgs e)
{
if (currentRec > 0)
currentRec--;
DisplayRec();
}
private void btnNEXT_Click(object sender, EventArgs e)
{
if (currentRec < addCount - 1)
currentRec++;
DisplayRec();
}
private void btnCLEAR_Click(object sender, EventArgs e)
{
txtEI.Clear();
txtNAME.Clear();
txtJOB.Clear();
txtADDRESS.Clear();
txtTELEPHONE.Clear();
txtEMAIL.Clear();
}
}
答案 0 :(得分:3)
1。 txtNAME不能留空,
识别,名称为null,空或WhiteSpace,您可以使用String.IsNullOrWhiteSpace()方法。
来自MSDN:String.IsNullOrWhiteSpace()
指示指定的字符串是null,空还是仅包含 白色空间字符。
试试这个:
if(!String.IsNullOrWhiteSpace(txtNAME.Text))
{
//continue
}
else
{
MessageBox.Show("Error");
}
2。 txtTELEPHONE应至少为10位数,
您可以使用String的Length
属性来识别电话号码是否有10位数。
试试这个:
if(txtTELEPHONE.Text.Length>=10)
{
//continue
}
else
{
MessageBox.Show("Error");
}
3。 txtEMAIL应采用电子邮件格式,并带有“@”和“。”
要验证EmailID,我建议您使用RegEx
,而不是只检查@
和.
个字符。
试试这个:正则表达式
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(txtEMAIL.Text);
if (match.Success)
{
//continue
}
else
{
MessageBox.Show("Error");
}
试试这个:如果您只想检查@
和.
字符
if(txtEMAIL.Text.Contains("@") && txtEMAIL.Text.Contains(".") )
{
//continue
}
else
{
MessageBox.Show("Error");
}
答案 1 :(得分:2)
在Save_click()方法中,调用方法ValidateEntries(),如下所示
private void btnSAVE_Click(object sender, EventArgs e)
{
if(validateEntries())
{
XmlTextWriter w = new XmlTextWriter(fn, Encoding.UTF8);
w.Formatting = Formatting.Indented;
w.WriteStartDocument();
w.WriteStartElement("employees");
for (int i = 0; i < addCount; i++)
{
w.WriteStartElement("employees");
w.WriteElementString("employeeID", employeeID[i].ToString());
w.WriteElementString("employeeName", employeeName[i]);
w.WriteElementString("jobTitle", jobTitle[i]);
w.WriteElementString("address", address[i]);
w.WriteElementString("telephoneNumber", telephoneNumber[i].ToString());
w.WriteElementString("email", email[i]);
w.WriteEndElement();
} w.WriteEndElement();
w.WriteEndDocument();
w.Close();
Application.Exit();
}
}
public bool VailidateEntries()
{
if (txtNAME.Text.Trim() == string.Empty)
{
MessageBox.Show("Name should not be empty");
txtNAME.Focus();
return false;
}
if (!(txtMailId.Text.Trim() == string.Empty))
{
if (!IsEmail(txtMailId.Text))
{
MessageBox.Show("Please enter valid Email Id's" );
txtMailId.Focus();
return false;
}
}
if (!(txtPhone.Text.Trim() == string.Empty))
{
if (!IsPhone(txtPhone.Text))
{
MessageBox.Show("Invalid Phone Number");
txtPhone.Focus();
return false;
}
}
}
private bool IsEmail(string strEmail)
{
Regex validateEmail = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
return validateEmail.IsMatch(strEmail);
}
private bool IsPhone(String strPhone)
{
Regex validatePhone = new Regex("^([0-9]{3}|[0-9]{3})([0-9]{3}|[0-9]{3})[0-9]{4}$");
return validatePhone.IsMatch(strPhone);
}
答案 2 :(得分:1)
我会考虑使用DataAnnotations并通过属性指定尽可能多的要求,其余部分由实现IValidatableObject
提供。将值添加到Employee
个对象的集合中,并使用Validator.ValidateObject
方法对它们运行验证。然后,您可以检查是否有任何返回的验证错误并执行相应的操作。
这也可能有助于您的XML序列化,因为您也可以使用XML属性对其进行注释以根据需要对其进行帮助 - 甚至可以创建包含类Employees
并进行设置以便您可以使用{{ 1}}为您自动创建XML。
XmlSerializer
答案 3 :(得分:0)
对于第三次验证,您可以使用C# Regex.Match 并通过学习正则表达式 The 30 Minute Regex Tutorial?
答案 4 :(得分:0)
使用正则表达式将是更好的选择,因为它将为您提供修改条件的灵活性。来自stackoverflow的有用链接。
答案 5 :(得分:0)
您正在寻找的是ErrorProvider。您可以使用它们来轻松验证Windows窗体的安静。我假设你经常使用设计模式,所以这对你来说是最好的解决方案,但不是你的代码质量。在工具栏中搜索ErrorProvider并将其添加到表单中。然后,您将在表单中将_ErrorProvider作为对象使用。然后,您只需在控件上绑定验证,例如:
txtTELEPHONE.Validating += ValidateName;
功能:
private void ValidateName(object sender, CancelEventArgs e)
{
// early initialization of errorMsg to fill it if necessary
string errorMsg = null;
// check your textbox
if (String.IsNullOrEmpty(txtNAME.Text))
{
errorMsg = "No name provided!";
}
// this is the interesting part
_ErrorProvider.SetError(lblTELEPHONE, errorMsg);
e.Cancel = errorMsg != null;
}
“_ErrorProvider.SetError”使用图标将错误消息绑定到文本字段的标签。如果用户将鼠标悬停在该图标上,则他或她可以看到错误消息。
有任何问题吗?随意问我:)