views:

40

answers:

3

Hello all,

I'm making an asp.net page with asp.net validation controls. If validation fails, I want to show a div (on the client). Where do I do this? I can't find a way to access the OnValidate event on the client. I can do this on the server, but I'd rather do it on the client.

A: 

You can either call a javascript function from the server side code using Page.RegisterClientScriptBlock Method]1

like

String scriptString = "<script type='text/javascript'>MakeDivVisible();</script>";
this.RegisterClientScriptBlock("clientScript", scriptString);

and then in the javascript function you can change the display of the div to be block like

document.getElementById("divId").style.display = 'block';

or if you give the div attribute runat="server" then you can access the div from the server side code and change its display to block

divId.Style["display"] = "block";
rahul
I only want to do it if the validation fails. And only on submit. And on the client.
cerhart
Then you can write the javascript code in the client itself inside the submit function and return false as the last step.
rahul
The problem is there is no submit function. I'm using the asp.net validation controls.
cerhart
A: 

Use an ASP.NET custom validator, http://www.google.ca/search?rlz=1C1CHNB_enCA344CA344&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=asp.net+custom+validator . If for some reason you can't/don't want to do that, use a ClientScriptManager.RegisterOnSubmitStatement method, http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registeronsubmitstatement.aspx, and ensure to return false in the client-side script if whatever you're validating fails.

nickyt
A: 

You will want to do the validation on the client and on the server, as you cannot guarantee that the client has JavaScript turned on. The following shows the steps to accomplish this on the client side, as implementing this on the server side should be trivial.

Given a simple div such as the following:

<div id="divErrors" runat="server" style="display: none;">
    This should only appear when validation fails.
</div>

Add the following JavaScript to your page:

<script language="javascript" type="text/javascript">
    function showErrors() {
        if (!Page_IsValid) {
            document.getElementById('divErrors').style.display = 'block';
        } else {
            document.getElementById('divErrors').style.display = 'none';
        }
    }
</script>

Finally, register a submit script that calls this new showErrors function (in the Page_Load event):

If Not Page.IsPostBack() Then
    Dim scriptName As String = "OnSubmitScript"
    Dim scriptType As Type = Me.GetType()
    Dim script As ClientScriptManager = Page.ClientScript
    If Not script.IsOnSubmitStatementRegistered(scriptType, scriptName) Then
        script.RegisterOnSubmitStatement(scriptType, _ 
                        scriptName, "showErrors();")
    End If
End If
Jason Berkan