Last active
May 27, 2023 11:29
-
-
Save meziantou/1755cd2d21c8a1d1d148 to your computer and use it in GitHub Desktop.
ASP.NET WebForms Validators & Bootstrap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ Page Language="C#" AutoEventWireup="true" %> | |
<!DOCTYPE html> | |
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head runat="server"> | |
<title>ASP.NET WebForms Validators & Bootstrap</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" /> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css" /> | |
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> | |
</head> | |
<body> | |
<form id="form1" runat="server"> | |
<asp:ScriptManager runat="server"></asp:ScriptManager> | |
<div style="padding: 50px;"> | |
<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="Veuillez saisir votre nom" /> | |
</div> | |
</div> | |
<script> | |
function extendedValidatorUpdateDisplay(obj) { | |
// Appelle la méthode originale | |
if (typeof originalValidatorUpdateDisplay === "function") { | |
originalValidatorUpdateDisplay(obj); | |
} | |
// Récupère l'état du control (valide ou invalide) | |
// et ajoute ou enlève la classe 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; | |
} | |
} | |
if (isValid) { | |
$(control).closest(".form-group").removeClass("has-error"); | |
} else { | |
$(control).closest(".form-group").addClass("has-error"); | |
} | |
} | |
} | |
// Remplace la méthode ValidatorUpdateDisplay | |
var originalValidatorUpdateDisplay = window.ValidatorUpdateDisplay; | |
window.ValidatorUpdateDisplay = extendedValidatorUpdateDisplay; | |
</script> | |
</form> | |
</body> | |
</html> |
Now it works perfect, thank you!!!
Excellent! I am just having troubles when using a form in an updatepanel. Any idea what I should do?
Wrap it inside
function pageLoad() {
}
Nice it works well. Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can I handle ValidationGroup with this script ?