Using RequiredFieldValidator to check if at least

2019-07-17 15:59发布

I have two textboxes on my asp.net page and a submit button. How can I use a single or more RequiredFieldValidators to check if at least one of the two textboxes has some text inside on submit button click?

3条回答
时光不老,我们不散
2楼-- · 2019-07-17 16:26

You can also use ClientValidationFunction attribute with CustomValidator and client side function

<asp:TextBox ID="txtBoxId1" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBoxId2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvId" runat="server" ClientValidationFunction="Validators.DoWork">
error</asp:CustomValidator>

<script language="javascript">
var Validators = {
DoWork: function (source, clientside_arguments) {

    var valid_val = true;

    //get the controls values using jQuery
    var txtBoxId1= $('input:text[id*=txtBoxId1]').val();
    var txtBoxId2= $('input:text[id*=txtBoxId2]').val();

    if (your condition) {
        valid_val = false;
    }

    clientside_arguments.IsValid = valid_val;
}
}
</script>
查看更多
We Are One
3楼-- · 2019-07-17 16:36

Along with two text boxes add a CustomValidator and call server side validation.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" OnServerValidate="CustomValidator_ServerValidate"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

Server side function

public void CustomValidator_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
    {
        args.IsValid = true;

        if (TextBox1.Text == "" && TextBox2.Text == "")
        {
            CustomValidator1.ErrorMessage = "Enter value in at least one text Box";
            args.IsValid = false;

        }
    }

Hope this helps you.

查看更多
Bombasti
4楼-- · 2019-07-17 16:48

First of all, if a field is not certainly required you shouldn't use a RequiredFieldValidator instead you can use a CustomValidator.

RequiredFieldValidator - Checks to make sure the user entered a value.

CustomValidator - Checks the form field's value against custom validation logic that you, the developer, provide.

This quote is from Using the CustomValidator Control By Scott Mitchell.

You can also check this Dynamically enable or disable RequiredFieldValidator based on value of DropDownList because if you are supposed to use a RequiredFieldValidator you will need to disable one of the two dynamically if one of the TextBox is valid.

查看更多
登录 后发表回答