views:

32

answers:

1

Hello,

I have an ASP .NET page with ASP validators (Required Field, Regular Expression,...) plus java script functions for additional validation (for example, to check if second date bigger than first date, among others).

I usually do:

<script type="text/javascript">

    function validate() {
        // ...
        alert('Not valid!');
        return false;
    }    
</script>


<asp:Button ID="Button1" runat="server" Text="Add" 
            OnClientClick="return validate();" OnClick="Button1_Click" />

So, the button advances to the postback if the asp and the javascript validation both pass, and it works fine.

I’m trying out the custom validator:

<asp:CustomValidator ID="CustomValidator1" 
EnableClientScript="true" runat="server" ControlToValidate="TextBox1" 
ClientValidationFunction="validate();" >
</asp:CustomValidator> 

(also tried with ClientValidationFunction="return validate();")

But the page is continuously advancing to the postback, even after showing the “not valid” alert... Any thoughts? Thanks!

+2  A: 

When using a CustomValidator, the client side validation function needs to accept a source and an arguments parameter. Then, to mark the validation as failed, you set arguments.IsValid to false. Here is the MSDN page for the CustomValidator.

function validate(source, arguments) {
   // ...

   alert('Not valid!');
   arguments.IsValid=false;
}
Jason Berkan
Beat me to it :)
cwap
you generally wouldn't use an `alert` in a validate function- the that's what the `Text` or `ErrorMessage` properties are for.
lincolnk
@lincolnk - True. I was just copying the example in the question and modifying it to show how you set the validation to a failed state.
Jason Berkan
Thanks! Yup, I was using the CustomValidator wrong.
naruu
I just used the alert as an example too (and a debugging helper). I used to use labels and styles (with javascript)... Will try out those attributes (Text,ErrorMessage) then... Thanks.
naruu