views:

30

answers:

2

Hi!

I have multiple text fields on form and i want two of them should validate like If one of them is empty then say "Both fields are required". Additionally I have also other text fields on form and they are already validating on button click.

Can it be handled using Asp.Net CustomValidator ?

A: 

Use a compare and require field validator, ie

<label>Password</label> <asp:TextBox runat="server" ID="txtPassword" MaxLength="15" TextMode="Password" />

<label>Password-check</label> <asp:TextBox runat="server" ID="txtPasswordCheck" TextMode="Password" MaxLength="15" />
<asp:RequiredFieldValidator runat="server" ID="rfvtxtPasswordCheck" ControlToValidate="txtPasswordCheck" Text="* " />
<asp:CompareValidator runat="server" ID="cvtxtPasswordCheck" ControlToValidate="txtPasswordCheck" ControlToCompare="txtPassword" Operator="Equal" Type="String" Text="* Passwords do not match" />
Jason Jong
+1  A: 

You can use custom validator to do this task.

<asp:CustomValidator ID="CustomValidator1" runat="server" 
            ErrorMessage="CustomValidator" ClientValidationFunction="testValid" 
            ControlToValidate="TextBox1" onservervalidate="CustomValidator1_ServerValidate" 
            ValidateEmptyText="True">both fields required</asp:CustomValidator> 

The ClientValidationFunction contains the client side javascript function testValid. so it should look like :

<script type="text/javascript">
        function testValid(sender, args) {
            ....you logic
            //set args.IsValid according to your logic 
            args.IsValid = false;
        }
    </script>

On server side,

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        //set args.IsValid according to your validation logic.
        args.IsValid = false;
    }
Adeel