I have this form with a custom validator, and Button. But, my custom Validator shows error only after button click. This is my validator, Button and code behind.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="User Name cannot be Empty!" ForeColor="Red" onservervalidate="CustomValidator1_ServerValidate" ControlToValidate="userNameTxt" ValidateEmptyText="True" ValidationGroup="save-valid"></asp:CustomValidator> <asp:Button ID="saveButton" runat="server" Text="Save" CssClass="save-button" onclick="saveButton_Click" TabIndex="7" ValidationGroup="save-valid" /> This is my code behind.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (IsUserValid(userNameTxt.Text)) { CustomValidator1.ErrorMessage = "User Name cannot be Empty!"; args.IsValid = false; } else args.IsValid = true; } protected void saveButton_Click(object sender, EventArgs e) { //This code executes regardless of CUstom Validator }