开发者

How do I hide a div (on the client) is client-side validation fails?

开发者 https://www.devze.com 2022-12-17 00:54 出处:网络
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 c

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 cli开发者_如何学Cent.


Use an ASP.NET custom validator.

If for some reason you can't/don't want to do that, use a ClientScriptManager.RegisterOnSubmitStatement method, and ensure to return false in the client-side script if whatever you're validating fails.


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";


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
0

精彩评论

暂无评论...
验证码 换一张
取 消