jQuery-validate error messages in Twitter…

6479 ワード


http://www.jefclaes.be/2012/11/jquery-validate-error-messages-in.html
 
 
something satis factory.In this example,I have a boot straphd form that looks like this.
@using (Html.BeginForm("ChangePassword", "Account", FormMethod.Post, new { @class = "form-horizontal"})) {
    <div class="control-group">

        <label class="control-label">Old password</label>

        <div class="controls">

            @Html.PasswordFor(m => m.OldPassword)                            

        </div>       

    </div>

    <div class="control-group">

        <label class="control-label">New password</label>

        <div class="controls">

            @Html.PasswordFor(m => m.NewPassword)                

        </div>

    </div>

    <div class="control-group">

        <label class="control-label">Confirm password</label>

        <div class="controls">

            @Html.PasswordFor(m => m.ConfirmPassword)                

        </div>                            

    </div>  

    <div class="control-group">

        <div class="controls">

            <button type="submit" class="btn btn-primary">Change password</button>

        </div>

    </div>

}
To make the error message show up in tooltips on the input controlls,I eventualy ended up with the snippet below.
$.validator.setDefaults({

    showErrors: function (errorMap, errorList) {

        this.defaultShowErrors();                            



        // destroy tooltips on valid elements                              

        $("." + this.settings.validClass)                    

            .tooltip("destroy");            



        // add/update tooltips 

        for (var i = 0; i < errorList.length; i++) {

            var error = errorList[i];

                         

            $("#" + error.element.id)

                .tooltip({ trigger: "focus" })

                .attr("data-original-title", error.message)                

        }

    }

});
I'm setting a custom show Errrors function to exted the behaviour of the jQuery validator.I don't to lose the default behaviour、so I start with invoking the default ShowErrofunction、to then destroy the tooltip on all valid input elemens and to finally add or udate the tooltip and its title on all invalid input elemens.The error List argment holds all the information I need formation Ian ary of invalid elemens and their cores ponding error messages.
[Object, Object]

> 0: Object

>> element: <input>

>> message: "The Current password field is required."

> 1: Object

>> element: <input>

>> message: "The New password field is required."

> length: 2
The end result looks like this.