Question

and I am a beginner in using asp.net and C# in visual studio 2008

I have a TextBox with the ID = LimitAmount, it is supposed to accepts input of type DOUBLE, therefore I made a CompareValidator (CompareValidatorAmount) to control this, now I want to get the TextBox Cleared after an invalid input type.

thank you !

Était-ce utile?

La solution

Use a custom validator:

  <asp:CustomValidator id="CustomValidator1"
       ControlToValidate="LimitAmount"
       OnServerValidate="ServerValidation"
       ErrorMessage="This field requires a number"
       ForeColor="red"
       runat="server"/>         

In the code behind:

  void ServerValidation(object source, ServerValidateEventArgs args)
  {
     double tmp;
     if(double.TryParse(args.Value, out tmp))
     {
        args.IsValid = true;
     }
     else
     {
        args.IsValid = false;
        LimitAmount.text = string.empty;
     }
  }

If you prefer, you can also validate this in Javascript with the ClientValidationFunction

Autres conseils

Please try using jQuery:

<table style="width: 100%;">
            <tr>
                <td style="width: 30%;">
                    <asp:TextBox ID="TextBox1" runat="server" onblur="return BtnClick();"></asp:TextBox>
                </td>
                <td style="width: 70%;">
                </td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" onblur="return BtnClick();"></asp:TextBox>
                </td>
                <td>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator"
                        ControlToCompare="TextBox1" ControlToValidate="TextBox2"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button2" runat="server" Text="Button" OnClientClick="return BtnClick();" />
                </td>
                <td>
                    &nbsp;
                </td>
            </tr>
        </table>

and the script

<script type="text/javascript">
    function BtnClick() {
        var val = Page_ClientValidate();
        if (!val) {
            var i = 0;
            for (; i < Page_Validators.length; i++) {
                if (!Page_Validators[i].isvalid) {
                    $("#" + Page_Validators[i].controltovalidate)
                    .val('');
                }
            }
        }
        return val;
    }
</script>

Try this........When validation is called

LimitAmount.text = string.empty ;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top