Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call RequiredFieldValidator on client before postback

I've inherited some code which breaks a page up into tabs using divs. On the first page there are many required field and regex validators. The problem is a user can switch to another tab, trigger a postback and fail the validators on the first page, leaving things in a mess.

What I want to be able to do is perform the validation on the first page as a user selects another tab, thus preventing them from moving 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 fire off the validators.

Thanks!

UPDATE: The answer provided by codeka is pretty close, however, because I need to provide both href and onclick attributes (to avoid messing up display), the tab (anchor) switch is still taking place even if validation fails. Here's how I solved this. 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 use of jQuery for cross-browser compatibility with click event. And this only works if there are no validators on other tabs, as per Thomas' answer, I'll need to use validation groups and extra logic in isValid if any get added.

like image 952
si618 Avatar asked Mar 22 '10 00:03

si618


1 Answers

ASP.NET creates a global javascript function Page_ClientValidate that you can call to fire the validators:

function isValid() {
    return Page_ClientValidate();
}
like image 99
Dean Harding Avatar answered Oct 23 '22 06:10

Dean Harding