Как проверить обязательный текст, когда опция “Other” выбрана из dropdownlist?

Это зависит от того, какие аргументы Вы имеете, но если они - много булевых значений/опций, возможно, Вы могли бы использовать Перечисление Флага?

6
задан Ahmad Mageed 14 September 2009 в 16:49
поделиться

2 ответа

None of the ASP.NET provided validators allow you to perform conditional validation based on another control. However, you can achieve this by using a CustomValidator that performs validation on the client-side, server-side, or both (at a minimum, server-side validation is recommended). The validators work well in conjunction with wizards.

ASP.NET markup example:

    <asp:DropDownList ID="OptionsDropDownList" runat="server">
        <asp:ListItem Text="Website" />
        <asp:ListItem Text="Search Engine" />
        <asp:ListItem Text="Other" />
    </asp:DropDownList>
    <asp:TextBox ID="OtherTextBox" runat="server" />
    <asp:CustomValidator ID="custvOptionsDropDownList" runat="server" ControlToValidate="OptionsDropDownList"
        ValidateEmptyText="true" Display="Dynamic" ClientValidationFunction="validateOtherTextBox"
        ErrorMessage="This field is required!" OnServerValidate="ValidateOtherTextBox" />

Javascript for ClientValidationFunction:

<script type="text/javascript" language="javascript">
    function validateOtherTextBox(event, args) {
        var textbox = document.getElementById('<%= OtherTextBox.ClientID %>').value;
        if (args.Value == 'Other')
            args.IsValid = (textbox != '');
        else
            args.IsValid = true;
    }
</script>

Code-Behind for OnServerValidate:

    protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args)
    {
        if (OptionsDropDownList.SelectedValue == "Other")
        {
            args.IsValid = (OtherTextBox.Text.Trim() != "");
        }
    }

Note that it's your choice to implement whatever you need. You could completely skip Javascript validation and remove that code and the ClientValidationFunction attribute. Also, notice that the Javascript refers to the target control by using the ClientID property. This is needed since ASP.NET assigns a different ID when the page is output and you'll want it to be provided to the Javascript method in this manner (view source on the page and you'll see that the control name has an extra prefix etc.).

9
ответ дан 10 December 2019 в 02:50
поделиться

вы затем проверяете, кто выбирает параметр в раскрывающемся списке, как этот

if (ddl.selecteditemindex == 1){
if (txtvalue.text == "")
{
alert('you write something if selected other otherwise choose from a list');
}
}
0
ответ дан 10 December 2019 в 02:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: