简体   繁体   English

C#Asp.net必填字段验证器

[英]C# Asp.net required field validator

I am new to ASP.NET. 我是ASP.NET的新手。

I have three ASP controls: textbox, dropdown and submit button. 我有三个ASP控件:文本框,下拉列表和提交按钮。

If the dropdown is selected, the textbox must be a required field and if dropdown is not selected textbox should not be required field. 如果选择了下拉列表,则文本框必须为必填字段,如果未选择下拉列表,则文本框不应为必填字段。 The challenge right now is that my required field validator fires even if dropdown is not selected. 现在的挑战是即使没有选择下拉菜单,我的必填字段验证器也会触发。

I'm using JavaScript to check if textbox is null and disable my required field. 我正在使用JavaScript检查文本框是否为空并禁用我的必填字段。

<td><label for="schoolName">SCHOOLNAMES</label></td>
   <td><asp:TextBox ID="txtschoolname" runat="server"></asp:TextBox>
       <asp:RequiredFieldValidator ID="RequiredFieldValidatorSchoolName"            runat="server" 
        ControlToValidate="txtschoolname" ForeColor="Red"   
       ErrorMessage="Required"></asp:RequiredFieldValidator>
   </td>
<td>Bank Name</td>
        <td>
          <select">
              <option>Please select the bank</option>
              <option value="DBN">DBN</option>
              <option value="CCC">CCC</option>
          </select>
        </td>

<td colspan="2">
        <asp:Button ID="Button1" runat="server" Text="submit"  
            OnClientClick=" validate();" onclick="Button1_Click"   />

JavaScript: JavaScript的:

function validate() {
    var txt = document.getElementById("txtschoolname");
    alert(txt);
    var ddlObj = document.getElementById("<%=txtschoolname.ClientID%>");
    var validatorObject = document.getElementById("<%=RequiredFieldValidatorSchoolName.ClientID%>");

    alert(ddlObj);
    if (txt == null) {
        validatorObject.enabled = false;
        //  validatorObject.isvalid = true;
    }
}

Check out this resource: https://msdn.microsoft.com/en-us/library/Aa479045.aspx 签出此资源: https : //msdn.microsoft.com/en-us/library/Aa479045.aspx

Take a look at the client side API's section, which indicates using the ValidatorEnable method to enable or disable the validator: 看一下客户端API的部分,该部分指示使用ValidatorEnable方法启用或禁用验证器:

ValidatorEnable('<%= RequiredFieldValidatorSchoolName.ClientID %>', false); //disable

You can do this with javascript, 您可以使用javascript执行此操作,

An exact question as been answered, Validation with checkbox , and it also caters for javsacript being disbaled. 回答了一个确切的问题,“ 带有复选框的验证” ,它还解决了javsacript被伪装的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM