ASP.NET WebForms Validators & Bootstrap

  • .NET
  • Web

ASP.NET WebForms has long been proposing a validation system for data entered by the user by the server and the client!

<div class="form-group">
   <asp:Label runat="server" CssClass="control-label" AssociatedControlID="Name" Text="Name" />
   <asp:TextBox runat="server" ID="Name" CssClass="form-control" />
   <asp:RequiredFieldValidator runat="server" CssClass="help-block"
   ControlToValidate="Name" ErrorMessage="Enter your name" />
</div>

When the textbox is empty, the error message specified appears:

OK but to integrate correctly with Bootstrap and to display red everywhere, it is also necessary to define the class has-error at the level of the enclosing div when the value is invalid.

For that we will simply replace, or rather extend, the JavaScript ValidatorUpdateDisplay method generated by ASP.NET WebForms:

function extendedValidatorUpdateDisplay(obj) {
    // call the original method to update the state of the controls
    if (typeof originalValidatorUpdateDisplay === "function") {
        originalValidatorUpdateDisplay(obj);
    }

    // Get the state of the control (valid or invalid)
    // and add or remove the class has-error
    var control = document.getElementById(obj.controltovalidate);
    if (control) {
        var isValid = true;
        for (var i = 0; i < control.Validators.length; i += 1) {
            if (!control.Validators[i].isvalid) {
                isValid = false;
                break;
            }
        }

        $(control).closest(".form-group").toggleClass("has-error", !isValid);
    }
}

// Replace the method ValidatorUpdateDisplay by our method
var originalValidatorUpdateDisplay = window.ValidatorUpdateDisplay;
window.ValidatorUpdateDisplay = extendedValidatorUpdateDisplay;

Here's the result:

Despite its age ASP.NET WebForms still allows to use the recent Frameworks without too much trouble 😃

As usual the complete code of the example is available on GitHub.

Do you have a question or a suggestion about this post? Contact me on Twitter or by email!

Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal