1

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 } 
1
  • 1
    server side validation only occurs on postback, such as on a button click. If you want it to run on something other than button click then you will need to put it in another event, such as texbox_changed event (if it's the username field). You will need to ensure the AutoPostBack property on the textbox is set to 'true' as well. Commented Mar 30, 2015 at 8:01

2 Answers 2

2

You can try to use client side validation.

<script type="text/jscript"> function textBoxControl(source,arguments){ if(arguments.Value.length >0) //or control things (e.g. at least 6 character) arguments.isValid = true; else arguments.isValid = false; } <script> 

Code behind is like below.

<asp:TextBox ID="userNameTxt" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" onservervalidate="CustomValidator1_ServerValidate" ControlToValidate="userNameTxt" ClientValidationFunction="textBoxControl"></asp:CustomValidator> 
Sign up to request clarification or add additional context in comments.

Comments

1

When I put the below code inside Save Button click, the problem gets solved.

 if (!Page.IsValid) return; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.