I have a long form for my users to fill out. Is there a way to hyperlink the error message in ValidationSummary to the specific开发者_运维百科 text field?
The easiest way to do this is with straightforward HTML anchor tags <a>
, you can include the HTML in the ErrorMessage
property of your validation control which will be displayed in your ValidationSummary
control. For examples
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="Button5" runat="server" Text="Submit" />
<br />
<div style="height:800px"></div>
<a name="TextBox1"></a>
Required Field
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Required Field is Required <a href='#TextBox1'>Click Here To Go To</a>"
Text="***"
ControlToValidate="TextBox1" />
A more elegant approach would be to combine the above approach with jQuery using the scrollTo
function and perhaps highlighting the field. You can include this jQuery/Javascript code in the onclick
property of the anchor tag.
I've implemented this before in the same way @jdmonty had suggested - by adding the anchor tags to each RFV's ErrorMessage attribute. Eventually I found this too tedious so I drummed up some jQuery to do the work for me. This snippet will wrap your validation messages in anchor tags with the href=#targetControl
, which of course when clicked scrolls to the target input.
Add this to the $(document).ready(); portion of your script code.
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function () {
//get target control and current error validation message from each validator
var errorMsg = $(this).context.errormessage;
var targetControl = $(this).context.controltovalidate;
var errorMsgWithLink = "<a href='#" + targetControl + "'> " + errorMsg + "</a>";
//update error message with anchor tag
$(this).context.errormessage = errorMsgWithLink;
});
You could add some additional jQuery as @jdmonty suggested to smooth the scrolling. You can also use the css pseudo class ':focus' in your style sheet to add styles for 'active' input textboxes, something like input[type=text]:focus{background-color:red;}
to really accentuate when they are focused.
P.S. I know this question is old but I just found it today while seeing if anyone had come up with a more elegant solution, so for anyone else in my shoes, here ya go.
精彩评论