Creating a custom response with ASP.NET validation controls

核能气质少年 提交于 2019-12-11 08:37:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!