How to do validation before form is submitted on client side in ASP.NET

I have an ASP.NET web form with validators that are disabled. I want to enable validators only AFTER Submit button is clicked and based on if the control is visible or not.

Here is my function:

protected void Submit_Click(object sender, System.EventArgs e)
{
if (ddlSite.Visible){    
  rfvSite.Enabled = true;
  base.Validate();
} else {
  rfvSite.Enabled = false;
}

The above code is working fine. But now I want to check if page is valid or not. If the page is Valid then I want to process the form. I don't know how to do this.

Answers


You have multiple options:

  1. Try to split your controls into multiple validation groups, which will only validate the controls in a specific group upon submit.

  2. Write your own custom validator. A custom validator can declare a client validation function and a server validation function. Creating a custom validator is well-documented.

  3. As StevieB mentioned, if you hide the controls server-side, the validators won't be fired. If the decision to hide them is made on the client, that's more difficult.

  4. Hook into the client-side validation functions and manipulate the validators. This can be difficult and may require changing internal ASP.Net scripts. Sometimes it's the only way to make web form validation do what you need it to. See this question for an example of extending/modifying validator behavior.

Since I'm new to asp.Net c#, I was wondering is someone can give me an example or idea as how to achieve this?

Consider using ASP.Net MVC instead of web forms. The web forms model is old and "fights" you on tasks like this. If you are just starting out, I'd suggest at least investigating MVC and see if your time is better spent.


A lot of jquery plugins was created for this reason : http://tinyurl.com/qetudk8


Need Your Help

bash ldap too long output

bash ldap openldap ldif

In Bash I would like to do an ldap query. It went well but in the output it cuts the end of the line when it's a long line.