开发者

How to call RequiredFieldValidator on client before postback

开发者 https://www.devze.com 2022-12-23 12:29 出处:网络
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

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.


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

function isValid() {
    return Page_ClientValidate();
}


You might try using a validation group per tab. On clicking from one tab to another, you would call something like so where the tab names represent the validation groups:

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

ADDITION I mentioned this in a comment, but I figured I would add it to my post. If there aren't any other validators on other tabs, then another solution would be to simply mark the other .NET controls on the other tabs that can trigger a postback with CausesValidation="false" (e.g. DropDownLists with AutoPostBack="true")

0

精彩评论

暂无评论...
验证码 换一张
取 消