开发者

Styling the relevant input on validation error, like MVC

I have search the net and not found anything that has helped, so thought I would ask on here.

I have a simple asp.net 2.0 form.

<form runat="server">
    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

    <asp:TextBox ID="txt1" runat="server" ValidationGroup="valGroup1"></asp:TextBox>
    <asp:RequiredFieldValidator ControlToValidate="txt1" ValidationGroup="valGroup1" runat="server" Display="Dynamic" ID="val1" ErrorMessage="*"></asp:RequiredFieldValidator>

    <asp:Button 开发者_高级运维ID="btn1" runat="server" ValidationGroup="valGroup1" CausesValidation="true" Text="submit" />
</form>

What I want to do is to change the styling on the input when validation fails for that particular input. Preferably by adding a class, not inline styles.

I can do this when javascript is not available via code behind, but what I want to do is have the same happen when javascript is available.

I know that ASP.NET injects a global js variable called Page_Validators, which is an array of all of the validator spans on the page. Is there an easier way to do this other than looping through all of these??

EDIT

I can sort of do it with the following:

<script type="text/javascript">

        function ValidateInputs() {

            var validators = Page_Validators;

            for (var i = 0; i < validators.length; i++) {
                var validator = validators[i];
                if (!validator.isvalid) {
                    document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
                }
            }

        }

    </script>

Was just wondering if there was a better way??

And can I get the microwoft validation scripts to call my validation method? or can I hook into the validation event manually?


That's a pretty good way of doing it; there is no public event or something else to tap into, unless you want to start replacing public events with your own custom ones (that gets messy).

HTH.


It turns out my answer is the only one that I am going to get!

<script type="text/javascript">

        function ValidateInputs() {


            Page_ClientValidate();//Validate the validators using microsofts validation

            var validators = Page_Validators;

            for (var i = 0; i < validators.length; i++) {
                var validator = validators[i];
                if (!validator.isvalid) {
                    document.getElementById(validator.controltovalidate).setAttribute("style", "border:solid 1px red;");
                }
            }

        }

    </script>

Also, on the button, set the OnClientClick="ValidateInputs();" to OnClientClick="ValidateInputs();return false;"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜