【发布时间】:2015-07-27 15:04:36
【问题描述】:
我无法使用 c# asp.net 验证空输入字段。其实我有两个输入字段。我需要显示空白输入字段的验证消息。我做了一些编码。当我在不提供任何输入的情况下单击提交按钮时,我收到第一个输入字段 i.e., Name field can not be blank 的错误消息,并且该输入字段上有一个红色边框。当我向第一个输入字段提供任何输入并再次单击提交按钮时,第二个输入字段的错误消息即将到来,但问题是边框颜色在第一个输入字段中显示为红色,这不应该出现。我在下面解释我的代码。
index.aspx:
<div class="widget-title">Doctor Registration <span id="validationMessage" runat="server" ></span></div>
<div class="row doctorlist-form">
<div class="col-md-6 bmargindiv1">
<label for="doctorname" accesskey="N"><span class="required">*</span> Name</label>
<div class="col-md-2 padding-zero">
<asp:DropDownList ID="txtdoctorprefix" name="doctorname" runat="server">
<asp:ListItem Value="Dr." Selected="True" Text="Dr."></asp:ListItem>
<asp:ListItem Value="Mr." Text="Mr."></asp:ListItem>
<asp:ListItem Value="Mrs." Text="Mrs."></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-10 padding-zero"><asp:TextBox ID="txtDoctorName" runat="server" oninput="detectName('dName');" ></asp:TextBox></div>
<div class="clearfix"></div>
</div>
<div class="col-md-6 bmargindiv1">
<label for="gender" accesskey="G"><span class="required">*</span> Gender</label>
<asp:DropDownList ID="txtGender" name="grnder" runat="server" onchange="selectGender('gender');">
<asp:ListItem Text="Select your Gender" Selected="True"></asp:ListItem>
<asp:ListItem Text="Male" Value="male" ></asp:ListItem>
<asp:ListItem Text="Female" Value="female"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-12 bmargindiv1">
<asp:Button runat="server" Text="Submit" class="button" ID="doctorDetails" OnClick="doctorDetails_Click" />
</div>
</div>
<script type="text/javascript">
function detectName(nameid) {
var type = nameid;
console.log(type);
switch (type) {
case 'dName':
$('#<%=txtDoctorName.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
function selectGender(type) {
var type = type;
switch (type) {
case 'gender':
$('#<%=txtGender.ClientID %>').css('border-color', '#e3e3e3');
$('#<%=validationMessage.ClientID %>').empty();
break;
}
}
</script>
index.aspx.cs:
protected void doctorDetails_Click(object sender, EventArgs e)
{
// Response.Write(txtDoctorName.Text.Trim().Length);
if (txtDoctorName.Text.Trim().Length == 0 )
{
validationMessage.InnerText = "Name field can not be blank.";
validationMessage.Style.Add("color", "red");
txtDoctorName.Focus();
txtDoctorName.BorderColor = System.Drawing.Color.Red;
return;
}
if (txtGender.SelectedIndex==0)
{
validationMessage.InnerText = "Gender field can not be blank.";
validationMessage.Style.Add("color", "red");
txtGender.Focus();
txtGender.BorderColor = System.Drawing.Color.Red;
return;
}
}
我的问题是当总字段为空白并且我单击提交按钮时,错误消息正确出现,但同时当我向第一个文本字段提供一些输入并再次单击提交按钮时,第一个 if 语句是也与不应该发生的第二个 if 语句一起执行。在这种情况下,只有第二个 if 语句应该执行。请帮我解决这个问题。
【问题讨论】:
-
您是否使用调试器单步执行
doctorDetails_Click事件?您是否也想过使用IsNullOrEmpty来检查txtDoctorName.Text 字段的输入 -
@ MethodMan :我也使用
IsNullOrEmpty进行了测试,但也存在问题。