Clienside validation before server side

可紊 提交于 2019-12-13 04:17:20

问题


My issues:

1) Postback always occurs

2) Is that the correct way to see if requiredFieldValidator is valid client side?

What I would like:

User clicks the visible click button.

This invokes isValid().

If page is valid then invoke server side function.

If page is invalid do alert.

<asp:Button ID="btnSubmit" runat="server" Text="Submit" ToolTip="Submit" CausesValidation="true" CssClass="blueNew buttonNew" 
                OnClientClick="isValid(); return false;" />

<div style="display: none;">
    <asp:Button ID="hiddenBtnSubmit" runat="server"  OnClick="btnSubmit_Click" />
 </div>

 <script>
function isValid() {
    if (Page_IsValid) {
        var button = document.getElementByID("<%=hiddenBtnSubmit.ClientID%>");
        button.click();
    } else {
        if (!reqFirstName.IsValid) {
            alert("First name is invalid");
        }
    }      
}
 </script>

回答1:


Nope, you just have to add the validators like this:

<asp:TextBox runat="server" ID="txtEmail" />
<asp:RequiredFieldValidator
    ErrorMessage="The email is required"
    ToolTip="The email is required"
    Text="(*)"
    ControlToValidate="txtEmail"
    runat="server" />
<asp:ValidationSummary runat="server" DisplayMode="BulletList" ShowMessageBox="true" />

And the validation will be executed on the client whenever you try to submit your form, you do not need to manually execute the validation

The output will be something like:

Edit 1

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

        return val;
    }
</script>

<asp:Button OnClientClick="return validate();" Text="Post" runat="server" />


来源:https://stackoverflow.com/questions/11443006/clienside-validation-before-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!