我正在尝试验证字段,因此用户无法使用空字段输入数据。问题是我仍在添加空字段,因此我的验证无效。
首先,我正在检查从组合框中选择的类型。然后我检查用户选择了哪种类型,然后根据类型我在输入数据之前检查空字符串的字段。
我在这里错过了什么吗?
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Multiple level field validations.
if (cmbType.SelectedIndex != -1)
{
if (cmbType.SelectedIndex == 0 &&
(txtUserName.Text != string.Empty ||
txtPassword.Text != string.Empty))
{
string SQL =
"INSERT INTO PersonalData([Type], [UserName], [Password]) " +
"VALUES(@Type, @UserName, @Password)";
InsertData(SQL);
}
else if (cmbType.SelectedIndex == 1 &&
(txtURL.Text != string.Empty ||
txtUserName.Text != string.Empty ||
txtPassword.Text != string.Empty))
{
// Creating SQL string. Using [] will prevent any erros
// that might occur if any other names will be reserved words.
string SQL =
"INSERT INTO PersonalData([Type], [URL], [UserName], [Password]) " +
"VALUES(@Type, @URL, @UserName, @Password)";
InsertData(SQL);
}
else if (cmbType.SelectedIndex == 2 &&
(txtSoftwareName.Text != string.Empty ||
txtSerialCode.Text != string.Empty))
{
// Creating SQL string. Using [] will prevent any erros
// that might occur if any other names will be reserved words.
string SQL =
"INSERT INTO PersonalData([Type], [SoftwareName], [SerialCode]) " +
"VALUES(@Type, @SoftwareName, @SerialCode)";
InsertData(SQL);
}
else
{
lblMessage.Text = "Please fill out all required fields!";
}
}
else
{
lblMessage.Text = "Please select a type first!";
}
}
答案 0 :(得分:4)
你确定你想要或潜在的领域而不是他们吗? 例如,
else if (cmbType.SelectedIndex == 1 &&
(txtURL.Text != string.Empty &&
txtUserName.Text != string.Empty &&
txtPassword.Text != string.Empty))
如果网址,用户名和密码都有值,则只允许您插入数据 - 在调用插入之前,只需使用或者只填充其中一个值,这意味着您可以拥有有效网址但不能输入密码和用户名。
答案 1 :(得分:2)
!string.IsNullOrEmpty(txtUserName.Text.Trim())
&& !string.IsNullOrEmpty(txtPassword.Text.Trim())
答案 2 :(得分:1)
这样的支票:
if(txtUserName.Text != string.Empty)
如果您的用户在txtUserName
中输入几个空格,则会传递。
您应该将所有支票更改为
if(txtUserName.Text.Trim() != string.Empty)
对.Trim()
的调用会删除任何尾随空格,然后会检查是否有任何遗留空间....