问题
I need to validate various ASP.NET controls, but instead of displaying the standard text/asterisk/image next to each when validation fails, I need to display custom content (change the outline color of the input textbox, display a tooltip, etc.). I could use a standard validation control in most cases (e.g., RequiredFieldValidator for a TextBox), except for the display when validation fails.
I've started out creating CustomValidators, but I need to do this many times for various validations (required field, regular expressions, ranges). It seems a waste to recreate the logic of these validators only so that it can change the response output. The MS documentation at http://msdn.microsoft.com/en-us/library/3w0bs977.aspx says a custom response can be done on both client and server in this case: "On both the client and server side you can create a custom response, such as a color change in a control or a font change for text on a label." It gives an example for the server side, but does not give a method for the client side. What is the best way to handle the custom response on the client?
回答1:
This article might help you:
http://msdn.microsoft.com/en-us/library/aa479045.aspx
Particularly this section (look for "Client Side Validation" then under there, "Special Effects"):
<asp:Label id=lblZip runat=server
Text="Zip Code:"/>
<asp:TextBox id=txtZip runat=server
OnChange="txtZipOnChange();" /></asp:TextBox><br>
<asp:RegularExpressionValidator id=valZip runat=server
ControlToValidate=txtZip
ErrorMessage="Invalid Zip Code"
ValidationExpression="[0-9]{5}" /><br>
<script language=javascript>
function txtZipOnChange() {
// Do nothing if client validation is not active
if (typeof(Page_Validators) == "undefined") return;
// Change the color of the label
lblZip.style.color = valZip.isvalid ? "Black" : "Red";
}
</script>
There is still some wiring up that needs to be done, which you may be able to tidy up with some jQuery or the like
来源:https://stackoverflow.com/questions/6891206/creating-a-custom-response-with-asp-net-validation-controls