How to call RequiredFieldValidator on the client before postback

I have inherited some code that breaks a page into tabs using a div. On the first page there are many required field validators and regular expressions. The problem is that the user can switch to another tab, cause a postback and skip the validators on the first page, leaving things in a mess.

What I want to do is check on the first page when the user selects another tab, thereby preventing the transition to a new tab until the first page is valid.

<ul> <li><a href="#tab1">Tab 1</a> </li> <li><a href="#tab2" onclick="return isValid();">Tab 2</a></li> <li><a href="#tab3" onclick="return isValid();">Tab 3</a></li> </ul> 

Where isValid needs to disable validators.

Thanks!

UPDATE: The answer provided by codeka is pretty close, however, since I need to provide the href and onclick attributes (to avoid messy display), the tab (anchor) switch still accepts even if the check fails. This is how I solved it. disclaimer: ugly code ahead

 <ul> <li><a id="tab1Tab" href="#tab1" style="display:none"/><a onclick="isValid('tab1');">Tab 1</a></li> <li><a id="tab2Tab" href="#tab2" style="display:none"/><a onclick="isValid('tab2');">Tab 2</a></li> <li><a id="tab3Tab" href="#tab3" style="display:none"/><a onclick="isValid('tab3');">Tab 3</a></li> </ul> function isValid(tab) { var valid = Page_ClientValidate(); var tabId = (valid ? tab : "tab1") + "Tab"; $("#" + tabId).click(); } 

Note the use of jQuery for cross-browser compatibility with the click event. And this only works if there are no validators on other tabs, since Thomas’s answer, I will need to use verification groups and additional logic in isValid if they are added.

+6
validation
source share
2 answers

ASP.NET creates the global javascript function Page_ClientValidate , which you can call to run validators:

 function isValid() { return Page_ClientValidate(); } 
+2
source share

You can try using a validation group for each tab. When you click one tab on another, you call something like this, where the tab names are validation groups:

 function TabValidate( tabName ) { if ( Page_ClientValidate( tabName ) ) { //do stuff } } 

APPENDIX I mentioned this in a comment, but decided that I would add it to my post. If there are no other validators on other tabs, another solution would be to simply mark other .NET controls on other tabs that can trigger a postback using CausesValidation = "false" (for example, DropDownLists with AutoPostBack = "true")

+2
source share

All Articles